Updated 2015-02-19 10:28:53 by PeterLewerin

Peter Lewerin (content disclaimer) 2014-02-19:

The term stack frame is based on the low-level implementation of the procedure of allocating memory for a proc to store its data objects (arguments, local variables, etc) in. Briefly, the execution stack is a linear structure holding data objects which is managed by setting a pointer to the latest object added to the stack: objects are discarded by moving that pointer back to the previous object, and so on. When a proc is called, each data object that it will use is added to the stack, together with the old value of the stack pointer, and the proc is then allowed to access each data object in the segment, or frame, between the places pointed to by the current value of the stack pointer (which might change: new data objects can be added to the stack after the proc is called, moving the stack pointer further) and the old value of the stack pointer. When the proc is done and returns, the stack pointer is reset to the old value, automatically discarding each object in the proc's stack frame. All of this is managed by the Tcl implementation and none of it requires the attention of the Tcl programmer.

There are a number of commands designed to cheat with this arrangement, such as global, which adds a global variable to the set of data objects the proc is allowed to access; uplevel, which allows a script to be evaluated in another stack frame; and upvar, which links a variable inside the proc's stack frame to a variable in another stack frame. (More properly, uplevel and upvar access other stack levels, which is a similar but not entirely equivalent thing, though somewhat conflated in Tcl's documentation.) The commands info frame and info level provide some information on the state of the stack.