Skip to content
Tcl Source Code Variables
Login

Variables

General Structure

Tcl internally has two main types of variables. These are variables that are in a Tcl_HashTable, and variables that are in a Local Variable Table (LVT) that is associated with a (procedure-like) stack frame. The variables in a hash table are larger than the variables in an LVT; they contain additional fields used to manage the variable in the context of the hash, but they share a common prefix structure; the Var struct. (A Tcl_Var is an opaque Var*.)

The Var has two fields: the flags and the value. The flags is an integer bit-set that's used to describe a whole bunch of things (such as whether the variable is a scalar, an array or a link to another variable). The value is a pointer, or rather more strictly it is a union of three pointers: a pointer to a Tcl_Obj* when the variable is a scalar, a pointer to a (specialisation of) Tcl_HashTable when the variable is an array, and a Var* when the variable is a link. When the pointer is NULL, the variable is considered to be unset. Variables in LVTs can have NULL values for as long as their stack frame persists, and variables in hash tables are usually removed as soon as their value becomes NULL (though not always; links and traces can keep them alive).

Access API

Internally, most of Tcl's considerable variable API funnels through a small set of core functions:

TclObjLookupVarEx is responsible for mapping a variable name (in one or two part form) to a Var* that can be accessed. It also does link traversal; the variable references it returns are to the variables that can actually be accessed, not their aliases. Where it can, it caches much of the interpretations of what it finds out in the Tcl_Obj references to the variable names; this is why it can be faster to use Tcl_ObjGetVar2 than Tcl_GetVar, though it is only really faster if you can handle the lifetime of the variable names usefully.

The other core part of Tcl's variable API are TclPtrGetVar, TclPtrSetVar, TclPtrIncrObjVar, and TclPtrUnsetVar. These are what actually do the reading, writing (including both append and lappend), incrementing and unsetting of variables, respectively.

With bytecode-compiled procedures, most of the calls to TclObjLookupVarEx are omitted because the variable references are converted into integer lookups into the LVT, which is far faster. Moreover, in the simplest cases the accesses to the variables by the other core API functions are also bypassed and the contents of the variables are accessed directly. It's only when the variables have things like traces or are accessed from outside the local context that the full API described above is used. Dynamic variable names always use the full API path.