Procs as variables

Richard Suchenwirth 2002-12-16 - Another thought experiment: how to implement variables with procs. This is in fact trivial - here's how to set such a variable:

 proc foo {} {return 42}

and it gets retrieved by bracketed call:

 puts [foo]

Procedures have the property that their names are visible in (at least) the defining namespace without need for declaration like global/variable. The downside is that they stay persistent until renamed away, while variables local to a procedure are automatically cleared up on return.

If you wish, you can of course sugar-wrap the above raw calls into a set look-alike:

 proc setp {name args} {
     switch [llength $args] {
        0   {#fall through}
        1   {proc $name {} [list return $args]}
        default {error "usage: setp name ?value?"}
 % setp foo 42
 % setp foo

See also procs as data structures for un-callable procs, and procs as objects for more complex state in procedures. The simple pattern above is sufficient for all values of a scalar variable.