我有以下基本代码:
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
程序的输出是这样的:
Inside: 4 5
Inside: 4 5
Inside: 4 5
outside 4, 5
现在我的困惑来自
my_var1
仅在 foreach 循环的局部范围内定义为什么它的值即使在循环外也可用?换句话说,是什么决定了 Tcl 中变量的范围?非常感谢您的帮助!
最佳答案
来自 the Tcl Manual :
Tcl evaluates variables within a scope delineated by procs, namespaces [...], and at the topmost level, the global scope.
因此 foreach 循环不会创建新的范围,并且所有变量都由 proc 限定范围。
关于tcl - Tcl 中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8859301/