Version 17 of Many ways to eval

Updated 2014-04-26 06:14:26 by RLE

In Tcl, There are many ways to evaluate a string as a script. This page, by Andreas Leitgeb, dgp, ms, pyk, rs, et al, enumerates them.

As implied by its name, eval is the most explicit way to evaluate a string as a script. In the following example, every command (except the first, of course, does the same thing: evaluates $cmd as a script.

set cmd {set name {Zaphod Beeblebrox}}

#these examples are not byte-compiled, so slower
eval $cmd
uplevel 0 $cmd
source nameoffile

#these examples are byte-compiled, so faster
if 1 $cmd
interp eval {} $cmd
namespace eval [namespace current] $cmd
proc {} {} [list uplevel $cmd]; {}
apply [list {} [list uplevel $cmd] [namespace current]]
apply [list argv {tailcall {*}$argv} [namespace current]] $argv

MS explained: "... eval does not bytecompile the script as it is "usually" used for one-time scripts.

The above examples all act like eval in the sense that they return the result of evaluating the script. The commands in the following example evaluate the string as a script, but don't return the result of the script:

foreach don't care $cmd
while 1 "$cmd; break"
interp alias {} breakable {} foreach _ _
breakable $cmd
catch $cmd
time $cmd
try $cmd

Taking it one step further, the following evaluation tactics not only don't return the result of evaluating the script, but don't evaluate it in the namespace they are called from:

after idle $cmd

See Also

   [Tcl chatroom], 2002-12-18: