首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在Tcl中使用upvar将变量传递给过程。

无法在Tcl中使用upvar将变量传递给过程。
EN

Stack Overflow用户
提问于 2011-10-21 09:01:51
回答 3查看 472关注 0票数 1

我需要一个能够从调用者的名称空间访问、读取和更改变量的过程。这个变量称为_current_selection。我尝试过用几种不同的方式使用upvar,但是没有什么效果。(我编写了小的测试程序来测试upvar机制)。以下是我的尝试:

打电话给proc:

代码语言:javascript
复制
select_shape $this _current_selection

proc:

代码语言:javascript
复制
proc select_shape {main_gui var_name} {
    upvar  $var_name curr_sel
    puts " previously changed:  $curr_sel"
    set curr_sel [$curr_sel + 1]
}

我第二次尝试:

打电话给proc:

代码语言:javascript
复制
select_shape $this

proc:

代码语言:javascript
复制
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命令进行的:

代码语言:javascript
复制
$this/zinc bind current <Button-1> [list select_shape $this _current_selection]

一开始我以为这不重要。但也许确实如此。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-10-21 12:40:05

我相信bind命令在全局命名空间中运行,因此应该在那里找到变量。这样做可能会奏效:

代码语言:javascript
复制
$this/zinc bind current <Button-1> \
    [list select_shape $this [namespace current]::_current_selection]
票数 4
EN

Stack Overflow用户

发布于 2011-10-21 09:49:54

要使upvar工作,变量必须存在于您要调用它的作用域中。考虑以下几点:

代码语言:javascript
复制
proc t {varName} {
   upvar $varName var
   puts $var
}

#set x 1
t x

如果您按原样运行它,您将得到所报告的错误,取消对set x 1行的注释,它将工作。

票数 3
EN

Stack Overflow用户

发布于 2011-10-21 10:10:06

在下面的示例中,我试图介绍来自其他命名空间的大多数变量的变化。它100%对我有用。也许会有帮助。

代码语言:javascript
复制
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 testC
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7847186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档