将 proc 变量导入命名空间
proc foo {param} {
namespace eval foo_ns {
uplevel {set foo_ns::x $param }
}
}
这看起来很丑。
[upvar] 将不起作用,因为它无法链接到“param”。
谢谢。
答案中的代码不起作用(tclsh8.4)
------------------------------------------------ ----
% proc bar {param} {
namespace eval foo_ns {
uplevel [list set foo_ns::x $param]
}
}
% bar 123
can't read "param": no such variable
----------------------------------------------------------
% proc foo {param} {
set ::foo_ns::x $param
}
% foo 123
can't set "::foo_ns::x": parent namespace doesn't exist
proc foo {param} {
namespace eval foo_ns {
uplevel {set foo_ns::x $param }
}
}
This just looks ugly.
[upvar] will not work, because it can't link to 'param'.
Thanks.
Code from answers does not work (tclsh8.4)
-------------------------------------------
% proc bar {param} {
namespace eval foo_ns {
uplevel [list set foo_ns::x $param]
}
}
% bar 123
can't read "param": no such variable
-------------------------------------------
% proc foo {param} {
set ::foo_ns::x $param
}
% foo 123
can't set "::foo_ns::x": parent namespace doesn't exist
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有什么问题:
在我的测试中,它似乎实现了相同的目标。
更新:感谢 K0re 指出了这一点。在调用 foo 之前,需要定义名称空间:
What is wrong with:
In my test, it seems to accomplish the same objective.
Update: Thanks To K0re for pointing this out. Before calling foo, you need to define the name space:
命名空间和级别是两个不同的东西。你不需要升级来解决这个问题。
这是一个简单的解决方案,它创建命名空间并在一行中设置变量:
Namespaces and levels are two different things. You don't need uplevel for this problem.
Here's a simple solution that creates the namespace and sets the variable in one line:
好吧,你有两个不同的问题。首先是命名空间尚不存在;第二个是您需要编写代码以便在该命名空间中创建/写入变量。总的来说,这只需要对 Hai 的代码进行微小的修改:
作为对您遇到的一些问题的评论:
这不起作用,因为您实际上是在说以下内容:
在命名空间“foo_ns”中,运行以下代码:
在堆栈的顶层,运行以下代码:
“set foo::x $param”
但是,在堆栈的顶层,变量“param”没有值(它仅在过程中定义。您需要确保它事先被替换。我会包括可以工作的代码,但老实说,我担心它会导致与问题的实际答案混淆......所以我将其省略。
Ok, you have two different problems. The first is that the namespace doesn't already exist; the second is that you need to write the code so that the variable is created/written in that namespace. Overall, this require only a tiny modification of Hai's code:
As commentary on some of the problems you were having:
This doesn't work because you are, effectively, saying the following:
in the namespace "foo_ns", run the following code:
at the top level of the stack, rung the following code:
"set foo::x $param"
However, at the top level of the stack, the variable "param" has no value (its only defined within the procedure. You'll need to make sure it gets substitured beforehand. I'd include code that would work but, honestly, I'm afraid it will cause confusion with the actual answer to the question... so I'll leave it out.