Is it possible to declare a static variable in Tcl?
I use a certain function to catch unknown command errors, and I want it to print an error message on th开发者_如何学Pythone first appearance of an unknown command - so I need to keep something like a static list inside theproc
. Is that possible?Or you can just use a straight global variable:
set varList {}
proc useCount {value} {
global varList ;
lappend varList $value
}
useCount One
useCount Two
puts $varList
No. But you can use a global (usually namespaced) array indexed by proc name for instance:
namespace eval foo {
variable statics
array set statics {}
}
...
proc ::foo::bar args {
variable statics
upvar 0 statics([lindex [info level 0] 0]) myvar
# use myvar
}
Tcl does not support static variable. Instead of using a global variable or a variable inside a namespace, another alternative is to implement your procedure as a method within a class (see [incr tcl] or snit). If you must implement static variable, the Tcl wiki has a page which discuss this issue: http://wiki.tcl.tk/1532
As I do not like global variables (unless you have a small script), I combine solutions from @kostix and @Jackson:
namespace eval foo {
variable varList {}
}
proc foo::useCount {value} {
variable varList
lappend varList $value
}
foo::useCount One
foo::useCount Two
puts $foo::varList
精彩评论