是否有任何可靠的机制来获取给定命名空间下使用“variable”关键字声明的所有变量?
例如,考虑以下代码:
namespace eval MyNamespace {
variable showThisVar1
set dontShowThisVar1 1
proc MyProc { } {
variable showThisVar2
set dontShowThisVar2 1
}
}
我正在寻找一种可靠的方法来获取 showThisVar1 和 showThisVar2,它们已在命名空间 MyNamespace 中声明为变量。查询结果不应返回 dontShowThisVar1 和 dontShowThisVar2。
最佳答案
您可以结合使用info vars
和info isn't
。
按原样运行代码后,您可以使用 info vars
获取 MyNamespace 中的所有变量。
> info vars MyNamespace::*
::MyNamespace::dontShowThisVar1
::MyNamespace::showThisVar1
首先请注意 showThisVar2
未列出。这是因为 MyNamespace::MyProc 尚未被调用。
> MyNamespace::MyProc
> info vars MyNamespace::*
::MyNamespace::showThisVar2
::MyNamespace::dontShowThisVar1
::MyNamespace::showThisVar1
调用该过程后,MyNamespace::showThisVar2
已在命名空间中声明。 dontShowThisVar2
不会出现在 info vars
的列表中,因为它的作用域为 proc。
要仅显示使用 variable
命令声明但未实际设置值的变量,您可以使用 info isn't
进行检查:
foreach var [info vars MyNamespace::*] {
if {![info exists $var]} {
puts $var
}
}
::MyNamespace::showThisVar2
::MyNamespace::showThisVar1
在回答您的问题之前,我没有意识到可以使用 info vars
返回变量,但不能使用 info contains
返回 1。
关于namespaces - Tcl:获取命名空间下定义的所有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73646395/