tcl - Tcl 中的变量范围

标签 tcl scope

我有以下基本代码:

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/

相关文章:

python - QFileSystemWatcher 不为另一个应用程序所做的更改发出 fileChanged 信号

javascript - 更新 $scope 不影响 View

laravel - 为 Laravel 5.5 中的所有模型制作自定义查询构建器方法(查询范围)

Python:如何在 eval 中访问 eval 的 globals()

javascript - 在循环中使用相同的变量来解决 "Closures in the loop"问题

c - 结构合法值约束配置继承

tcl - 随机颜色生成器,生成可以在 TCL 中明显区分的颜色

python - Tk/Tkinter Canvas "<ItemDelete>"事件?

javascript - BackboneJS : Avoid calling _. 绑定(bind)()

tcl - 返回码错误和错误有什么区别