global a b != global a; global b in this circumstance

global a b != global a; global b in this circumstance

Post by ewilsonmai » Sun, 18 Nov 2007 22:14:38


I had to quickly hack a script and came across a "gotcha" that wasn't
obvious because of a well-placed catch.

Here is a script that shows the problem:

#----------------------------
set x 1
set y1 "y1"

proc ok {} {
global x
global y$x
puts "$x [set y$x]"
}

proc fail {} {
global x y$x
puts "$x [set y$x]"
}

ok
fail
#----------------------------

Regards
E Wilson
 
 
 

global a b != global a; global b in this circumstance

Post by Uwe Klei » Sun, 18 Nov 2007 22:47:04


Ha, that answers my question, it is not Evil Son then ;-)

all tokens of a line are evaluated ($ substitution [] substitution
{*} expansion _and then_ this list is run as a command (item1) with
arguments Item-2 .. Item-last.
Thus $x must resolve _before_ the command [global] sees any of this.

uwe

 
 
 

global a b != global a; global b in this circumstance

Post by ewilsonmai » Sun, 18 Nov 2007 23:38:15

On Nov 17, 11:47 pm, Uwe Klein < XXXX@XXXXX.COM >



Ah, thanks for that clear explanation.

Evil son :-)
 
 
 

global a b != global a; global b in this circumstance

Post by Bryan Oakl » Sun, 18 Nov 2007 23:43:44


Do you understand why this is so? It's an important lesson to learn
about Tcl.

The explanation is pretty simple: tcl expands all variables before
calling the command. So, y$x is expanded, and _then_ passed to the
global command. At the point in time that y$x is expanded, x is undefined.