Richeek
Richeek

Reputation: 2220

Variable Scope in Tcl

I have the following basic code:

proc test {} { 
    set my_var2 3
    foreach iter {1 2 3} {
        set my_var1 4
        set my_var2 5
        puts "Inside: $my_var1 $my_var2\n"  
    }
    puts "outside $my_var1, $my_var2\n"    ;#WHY IT DOES NOT GIVE ERROR HERE!
}
test  ;#calling the function

The output of the program is this:

Inside: 4 5

Inside: 4 5

Inside: 4 5

outside 4, 5

Now my confusion is since my_var1 is define only in the local scope of foreach loop why its value is available even outside the loop? In other words what determines the scope of a variable in Tcl? Thanks a lot for the help!

Upvotes: 3

Views: 4526

Answers (1)

Ergwun
Ergwun

Reputation: 12978

From the Tcl Manual:

Tcl evaluates variables within a scope delineated by procs, namespaces [...], and at the topmost level, the global scope.

So the foreach loop does not create a new scope and all your variables are scoped by the proc.

Upvotes: 15

Related Questions