TCL Training Series - upvar

TCL Training Series - upvar

We have seen the command “uplevel” and how to use it earlier. Now, let’s look into a related command upvar.

Syntax The TCL language reference manual gives the following description for the command. upvar ?level? otherVar myVar ?otherVar myVar ...?

`This command arranges for one or more local variables in the current procedure to refer to variables in an enclosing procedure call or to global variables. Level may have any of the forms permitted for the uplevel command, and may be omitted if the first letter of the first otherVar isn't # or a digit (it defaults to 1). For each otherVar argument, upvar makes the variable by that name in the procedure frame given by level (or at global level, if level is #0) accessible in the current procedure by the name given in the corresponding myVar argument. MyVar is always treated as the name of a variable, not an array element. OtherVar may refer to a scalar variable, an array, or an array element.`

Now let’s see one simple program and its output. In the following code, there are three levels. Level#0 or the top level calls the procedure "a" which is level#1. The variable x is set to 1 in procedure a, and procedure a in turn calls procedure "b", which is level#2. At this level, there is an upvar call that refers to the x value 2 levels up.

set x 0; #Value of x at level 0. proc b num { upvar 2 $num x puts "x in b: $x"; } proc a {} { set x 1 b x; puts "x in a: $x"; } a;

Now run this program, and you should see:

Variable x is assigned in level#2 the value it had in top level.