Amir Rachum
Amir Rachum

Reputation: 79725

Static variable in Tcl

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 the first appearance of an unknown command - so I need to keep something like a static list inside the proc. Is that possible?

Upvotes: 7

Views: 4249

Answers (4)

Roalt
Roalt

Reputation: 8450

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

Upvotes: 1

Hai Vu
Hai Vu

Reputation: 40773

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

Upvotes: 2

Jackson
Jackson

Reputation: 5657

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

Upvotes: 4

kostix
kostix

Reputation: 55563

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
}

Upvotes: 2

Related Questions