无法定义全局定义的命名空间变量 TCL

Cannot define namespace variable which was defined globally TCL

我无法在先前在全局范围内定义的名称空间(在 TCL 中)中定义变量。看我的例子:

xsct% $tcl_version
[8.5]
xsct% set foo 1
1
xsct% $foo
[1]
xsct% namespace eval ns {
set foo 2
set bar 3
}
3
xsct% $::ns::bar
[3]
xsct% $::ns::foo
can't read "::ns::foo": no such variable
xsct%

我在网上重现了这个问题:http://tpcg.io/3SIBYG

如何独立于全局范围在命名空间中定义变量?

我使用:

至少在第一次访问它们时,始终使用 variable 命令在命名空间中定义变量,否则您最终会使用 命名空间变量解析规则 接管和让你的生活变得不愉快。它们很奇怪(尽管实际上与命令解析的工作方式非常相似)并且您几乎不需要它们,并且可能会在 Tcl 9 中被删除。但是在那之前,您只能做:

namespace eval ns {
    variable foo 2
    variable bar 3
}

或:

namespace eval ns {
    variable foo
    set foo 2
    variable bar
    set bar 3
}

如果你想做数组,你可以。他们这样做吗(variable 只有一个参数):

namespace eval ns {
    variable ary
    array set ary {foo 2 bar 3}
}

variable 命令实际上做的是使命名空间 中的变量处于 unset 状态 以便在 [=17] 这样的命令时它仍然解析=] 和 array 可以找到变量并写入它。