我需要一个能够从调用者的名称空间访问、读取和更改变量的过程。这个变量称为_current_selection。我尝试过用几种不同的方式使用upvar,但是没有什么效果。(我编写了小的测试程序来测试upvar机制)。以下是我的尝试:
打电话给proc:
select_shape $this _current_selectionproc:
proc select_shape {main_gui var_name} {
upvar $var_name curr_sel
puts " previously changed: $curr_sel"
set curr_sel [$curr_sel + 1]
}我第二次尝试:
打电话给proc:
select_shape $thisproc:
proc select_shape {main_gui} {
upvar _current_selection curr_sel
puts " previously changed: $curr_sel"
set curr_sel [$curr_sel + 1]
}在所有的尝试中,一旦它在代码中到达这个区域,它就会说can't read "curr_sel": no such variable
我做错了什么?
编辑:
函数的调用是通过bind命令进行的:
$this/zinc bind current <Button-1> [list select_shape $this _current_selection]一开始我以为这不重要。但也许确实如此。
发布于 2011-10-21 12:40:05
我相信bind命令在全局命名空间中运行,因此应该在那里找到变量。这样做可能会奏效:
$this/zinc bind current <Button-1> \
[list select_shape $this [namespace current]::_current_selection]发布于 2011-10-21 09:49:54
要使upvar工作,变量必须存在于您要调用它的作用域中。考虑以下几点:
proc t {varName} {
upvar $varName var
puts $var
}
#set x 1
t x如果您按原样运行它,您将得到所报告的错误,取消对set x 1行的注释,它将工作。
发布于 2011-10-21 10:10:06
在下面的示例中,我试图介绍来自其他命名空间的大多数变量的变化。它100%对我有用。也许会有帮助。
proc select_shape {main_gui var_name} {
upvar $var_name curr_sel
puts " previously changed: $curr_sel"
incr curr_sel
}
namespace eval N {
variable _current_selection 1
variable this "some_value"
proc testN1 {} {
variable _current_selection
variable this
select_shape $this _current_selection
puts " new: $_current_selection"
}
# using absolute namespace name
proc testN2 {} {
select_shape [set [namespace current]::this] [namespace current]::_current_selection
puts " new: [set [namespace current]::_current_selection]"
}
select_shape $this _current_selection
puts " new: $_current_selection"
}
N::testN1
N::testN2
#-------------------------------------
# Example with Itcl class
package require Itcl
itcl::class C {
private variable _current_selection 10
public method testC {} {
select_shape $this [itcl::scope _current_selection]
puts " new: $_current_selection"
}
}
set c [C #auto]
$c testChttps://stackoverflow.com/questions/7847186
复制相似问题