【发布时间】:2014-09-20 10:24:56
【问题描述】:
在 Tcl 中,我正在尝试处理命名空间,但遇到了以下问题。
我的代码如下。
% namespace eval counter {
#Declaring the variable 'num' in counter namespace
variable num 0
proc next { } {
#Accessing 'num' here, since we have already declared it in it's namespace
return [ incr num ]
}
proc reset { } {
#Same as above
return [ set num 0 ]
}
}
%########OUTPUT############
% ::counter::next
1
% ::counter::next
1
% ::counter::reset
0
% ::counter::next
1
如您所见,我可以毫无问题地访问值“num”。但是,值 'num' 保留了每次调用的值。
通过在每个过程中声明变量“num”,保留值。
% namespace eval counter {
variable num 0
proc next { } {
variable num
return [ incr num ]
}
proc reset { } {
variable num
return [ set num 0 ]
}
}
% ######OUTPUT#########
% ::counter::next
1
% ::counter::next
2
% ::counter::next
3
% ::counter::reset
0
为什么会有这种行为?
在程序内部也声明变量有什么意义?
【问题讨论】:
标签: namespaces tcl scope