Frag Logo
  Frag Home | Frag SF Project   index | contents | previous | next

Evaluating Code Using "eval"

eval is used to dynamically evaluate the code given by the <code> argument. It can optionally have the eval -uplevel ?levels? argument, which allows code to be evaluated levels level up the callstack. The default value for the option levels argument is 1, which means that the code will be evaluated in the calling callframe.

Another option is to use eval -global. This option evaluates the code in the global callframe. Please note that in general, it is recommended to avoid the use of global variables, which could be accessed via this option.

The syntax is:
eval ?-uplevel ?levels?|-global? <code>
The following code produces some code on the fly (it creates a number of class objects X_1 X_2 X_3), and then the produced code is executed via eval.
set code ""
foreach cl {X_1 X_2 X_3} {
    set code [string append $code "  Object create $cl\n"]
}
puts "Code produced: \n$code"
eval $code
The following command uses the uplevel option to read a variable from the calling callframe:
Command create c1 -cmd {} {
    eval -uplevel {get ix}
}
set ix 1
puts "ix = [c1]"
Because in this example the variable ix is defined at the global callframe, eval -global {get ix} would produce the same result.

  index | contents | previous | next