如何访问过程之外的变量

the*_*413 2 variables scope tcl global-variables

我正在尝试围绕 Tcl 变量作用域进行思考,但我坚持认为是一个简单的概念:如何访问我在过程之外定义的变量,但我没有明确地定义该变量传递给进程?

我试图避免设置一堆全局变量,并且只访问我在特定命名空间中定义的变量。我需要在下面的代码中添加什么,以便 proc 可以访问变量a,这显然不在 proc 的范围内?

set a apples
proc myList {b c} {
   puts [concat $a $b $c]
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*rry 5

您可以使用upvar

set a apples
proc myList {b c} {
    upvar a a
    puts [concat $a $b $c]
}
Run Code Online (Sandbox Code Playgroud)

或者,稍微扩展示例以显示“源”变量不必存在于全局范围内:

proc p1 {} { set a 10; p2 }
proc p2 {} { upvar 1 a b; puts "in p2, value is $b" }
p1
Run Code Online (Sandbox Code Playgroud)

输出

in p2, value is 10
Run Code Online (Sandbox Code Playgroud)

如果a在命名空间中定义,您可以使用variable

namespace eval foo {
    set a apples
    # OR
    # variable a apples
}

proc foo::myList {b c} {
    variable a
    puts [concat $a $b $c]
}
Run Code Online (Sandbox Code Playgroud)

或者,如果a是在全局范围内创建的,您仍然可以在没有该global函数的情况下访问它,使用::(我将引用这个SO问题):

proc myList {b c} {
    puts [concat $::a $b $c]
}
Run Code Online (Sandbox Code Playgroud)