[Solved] Which is better way? Variables related


If in a namespace eval, use variable to avoid the weirdness of the variable name resolver. (I don’t want to describe in detail what it does, other than to say that code that relies on it can be automatically described as buggy and in hard to accurately describe ways.)

If in a procedure, (usually) use set unless you want a local variable (with the same name as the last component of the namespace variable) that is coupled to the local variable so any manipulation of one is a manipulation of the other. For example, if you do:

variable foobar::grill "sprocket"

The local variable grill will be created and bound to the namespace variable grill in the namespace foobar (either relative to the current namespace or to the global namespace; this is “namespace resolution” and it is simpler than variable resolution, mentioned above!). The namespace variable grill, if it didn’t already exist, will be specially flagged as existing (but initially unset). Finally, because we did supply a value (sprocket) that will be stored into the namespace variable (and hence also appear in the local variable).

If you are going to read or write a namespace variable multiple times in a procedure, it is considerably faster to bind it to a local variable and work on that instead. Once bound, you can’t really unbind them, but it is usually not a problem. (Note that the binding process is effectively the same when you use upvar or global or namespace upvar, though each has different ways to look up what it is binding to.)


If you’re doing all this to simulate classes, consider using real classes instead. There’s a few options (incr Tcl, XOTcl, TclOO, Snit).

2

solved Which is better way? Variables related