TCL-将多个变量设置为0

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

我有很多counts变量(即:count1 count2 count3...。]

set count1 0
set count2 0
set count3 0

不是在单独的行上键入所有内容,而是在TCL中有一种更短的方法来仅设置所有count1 ..... count100 0

即:设置count1 [列表....]

tcl var multiple
2个回答
1
投票

如果您有这么多紧密相关的变量,我建议您改用数组,并且可以对其使用循环:

for {set i 0} {$i <= 100} {incr i} {
    set count($i) 0
}

这样,如果您不需要计数,就可以随时取消设置数组并相当容易且快速地释放一些内存。

如果由于某种原因您不能使用数组而不是普通变量,那么您仍然可以这样做:

for {set i 0} {$i <= 100} {incr i} {
    set count$i 0
}

如果变量彼此之间的关联度不是很高,并且它们之间的联系并不多,则可以像这样使用lassignlrepeat

lrepeat

在上面,lassign [lrepeat 4 0] a b c d 将创建一个包含元素lrepeat的列表4次。


0
投票

我有很多counts变量(即:count1 count2 count3...。]

不要,仅维护一个Tcl列表并通过其列表位置访问各种计数:

0

[如果您仍然想将计数的列表编码“分解”为专用变量的集合,这是使用set count [list 0 0 0 0]; # This is your "multi-set" lindex $count 0; # a.k.a. $count0 or [set count0] lset count 0 5; # a.k.a. [set count0 5] lindex $count 1; # a.k.a. $count1 lset count 1 10; # a.k.a. [set count1 10] 的杰里建议的广义变体,然后:

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