tcl - TCL中upvar 0和upvar 1的区别

标签 tcl upvar

谁能告诉我 upvar 0 之间的区别和 upvar 1在TCL中,我们如何才能实时使用。拜托,如果有人用例子来解释,它让我更清楚。

最佳答案

当您调用一堆过程时,您会得到一堆堆栈帧。它在名称中。我们可以这样想象:

abc 123 456
   bcd 321 456
      cde 654 321

OK, so we've got abc calling bcd calling cde. Simple.

The 0 and 1 in upvar say how many levels to go up the stack when looking up the variable to link to. 1 means go up one level (i.e., to the caller of the current frame), say from cde to bcd in our example, 2 would go from cde up to abc and 3 all the way up to the global evaluation level where overall scripts and callbacks run. 0 is a special case of this; it means do the lookup in the current stack frame. There's also the ability to use indexing from the base of the stack by putting # in front of the name, so #0 indicates the global frame, #1 the first thing it calls.

The most common use of upvar is upvar 1 (and if you leave the level out, that's what it does). upvar 0 is only really used when you want to get a different (usually easier to work with) name for a variable. The next most common one is upvar #0, though global is a much more common shorthand there (which matches the unqualified parts of the name for your convenience). Other forms are rare; for example, upvar 2 is usually an indication of really confusing and tangled code, and hardly anyone ever used upvar #1 before Tcl 8.6's coroutines. I've never seen upvar 3 or upvar #2 in the wild (though computed level indicators are present in some object systems for Tcl).

Example of upvar 1 — pass variable by name:

proc mult-by {varName multiplier} {
    upvar 1 $varName var
    set var [expr {$var * $multiplier}]
}

set x 2
mult-by x 13
puts "x is now $x"
# x is now 26
upvar 0 示例——简化变量名:
proc remember {name contents} {
    global my_memory_array
    upvar 0 my_memory_array($name) var
    if {[info exist var]} {
        set var "\"$var $contents\""
    } else {
        set var "\"$name $contents\""
    }
}

remember x 123
remember y 234
remember x 345
remember y 456
parray my_memory_array
# my_memory_array(x) = ""x 123" 345"
# my_memory_array(y) = ""y 234" 456"

关于tcl - TCL中upvar 0和upvar 1的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30189782/

相关文章:

linux - 如何从 TCL shell 执行 Linux 命令?

namespaces - 从带有 force 选项的命名空间导入 procs 后,全局命名空间中的 procs 在某些条件下由 auto_load 使用

tcl - upvar 的作用是什么?

TCL - 返回变量与 upvar 并修改

namespaces - 如何通过 tk 窗口按名称更新变量

regex - 限制 regsub 命令的数量以删除列表中的空格、行尾或回车符

tcl - 是否可以更改笔记本标签的宽度?

TCL::如何将反斜杠 "\"作为常规字符

Tcl upvar 到另一个过程中的变量