Reputation: 3235
I am puzzled at TCL's variable scope rule, here is an experiment:
if {2 > 1} {
set x 100
}
proc p1 {} {
set y 200
}
puts $x
p1
puts $y
Running the script gives me:
100
can't read "y": no such variable
while executing
"puts $y"
This puzzled me: the error about $y makes sense because y is defined inside proc, so it is not accessible outside the proc. The problem is x, why is it accessible? It is defined in a nesting script of "if" command.
From my habitual thinking from C++ point of view, it does not make sense. Does TCL have special treatment of command "proc" so that the variables declared in its nesting script are dealt differently from others, such as "if", "for", etc.?
BTW I know how to make it work, just want to understand the TCL rules on variable scope.
Upvotes: 1
Views: 1209
Reputation: 5723
The only scoping in Tcl is within a proc or a namespace eval
.
Braces are containers (of a script or a string), not groups, and do not define a new scope.
The if statement consists of: if
followed by an expr followed by a body. Both expr and body are just strings which contain an expression and a script.
Remember that Tcl is not an Algol derived language, and you cannot transfer rules from C over to Tcl.
Upvotes: 4