Static variable in Tcl

Is it possible to declare a static variable in Tcl?
I use a specific function to detect unknown command errors, and I want it to print an error message the first time an unknown command appears, so I need to save something like a static list inside proc . Is it possible?

+6
source share
4 answers

Or you can just use a direct global variable:

 set varList {} proc useCount {value} { global varList ; lappend varList $value } useCount One useCount Two puts $varList 
+4
source

Not. But you can use a global (usually named) array indexed by proc, for example:

 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 } 
+2
source

Tcl does not support a static variable. Instead of using a global variable or a variable inside a namespace, another alternative is to implement your procedure as a method inside a class (see [Incr tcl] or snit). If you must implement a static variable, there is a page on the Tcl wiki that discusses this problem: http://wiki.tcl.tk/1532

+2
source

Since I don't like global variables (unless you have a small script), I combine the 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 
0
source

Source: https://habr.com/ru/post/888993/


All Articles