1

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.

1
  • If you run your p1 command's script inside an uplevel, it will also behave the same way as the if command. e.g. proc p1 {} { uplevel { ... } }. Commented Apr 27, 2016 at 22:48

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.