gpt4 book ai didi

tcl - Tcl 中的变量范围

转载 作者:行者123 更新时间:2023-12-04 22:21:58 30 4
gpt4 key购买 nike

我有以下基本代码:

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com