I’m fairly new to TCL, and am providing QA on some code developed by others (no really!). There are lots and lots of global variables in this particular program, and I sometimes see upvar used, often in conjunction with global. I understand that upvar emulates pass-by-reference, but what would be the practical difference be between the two following procs?
set myBigFatGloblVariable 'hello' proc myFirstProc { var1 var2 } { upvar 1 $var1 local set local [expr $var2 * 3] } proc mySecondProc { var2 } { global myBigFatGlobalVariable set $myBigFatGlobalVariable [expr $var2 * 3] } myFirstProc $myBigFatGlobalVariable 3 mySecondProc 3
It seems to me that myFirstProc would be cleaner and . Am I missing something here?
The big difference between your two procs is this: myFirstProc sets the global ‘hello’, mySecondProc sets the local ‘hello’.
mySecondProc references the global myBigFat… to get the value ‘hello’, but does not alter the scope of the ‘hello’ variable.
myFirstProc receives the value ‘hello’ as a parameter, and then creates a link between a variable named ‘hello’ one frame up the stack and the local variable ‘local’. Setting ‘local’ has the effect of setting ‘hello’ one frame up the stack.
To see:
If you really want to set the global ‘hello’ from mySecondProc, you’ll need to add
global $myBigFatGlobalVariable