在tcl中将变量从低位proc传递到高位proc

问题描述 投票:0回答:1

我有以下代码,它在内部循环中输出相同的变量c值。

global c

proc one { a c } {
    for {set i $a} {$i < 10} {incr i} {
        two $c
    }
}

proc two { c } {
     incr c
     puts "Value of c is $c"
}

当我使用以下输入运行它时:

two 0 3

它打印10次“ c的值为4”,而不是不断将循环内的c的值从4增加到13。

问题是来自过程2的c的值没有再次传递到for循环,并且它从过程1解析器c获得的值与3相同。如何获得所需的输出?

variables nested tcl proc
1个回答
1
投票

听起来您想将变量cproc one传递到proc two 通过引用,以便将变量值的更改反映回调用者中。

tcl中完成此操作的一种方法是传递变量的[[name,并使用upvar命令,如下所示:

proc one { a c } { for {set i $a} {$i < 10} {incr i} { two c ;# <= note: passing 'c' by name, not by value } } proc two { c_name } { upvar $c_name c ;# <= note: c in this proc is using callers variable incr c puts "Value of c is $c" } one 0 3
上面产生了以下输出:

Value of c is 4 Value of c is 5 Value of c is 6 Value of c is 7 Value of c is 8 Value of c is 9 Value of c is 10 Value of c is 11 Value of c is 12 Value of c is 13

© www.soinside.com 2019 - 2024. All rights reserved.