Next: , Previous: , Up: Variable Scoping   [Contents][Index]


16.8.3 Implementation of Dynamic Scoping

A simple sample implementation (which is not how SXEmacs Lisp actually works) may help you understand dynamic binding. This technique is called deep binding and was used in early Lisp systems.

Suppose there is a stack of bindings: variable-value pairs. At entry to a function or to a let form, we can push bindings on the stack for the arguments or local variables created there. We can pop those bindings from the stack at exit from the binding construct.

We can find the value of a variable by searching the stack from top to bottom for a binding for that variable; the value from that binding is the value of the variable. To set the variable, we search for the current binding, then store the new value into that binding.

As you can see, a function’s bindings remain in effect as long as it continues execution, even during its calls to other functions. That is why we say the extent of the binding is dynamic. And any other function can refer to the bindings, if it uses the same variables while the bindings are in effect. That is why we say the scope is indefinite.

The actual implementation of variable scoping in SXEmacs Lisp uses a technique called shallow binding. Each variable has a standard place in which its current value is always found—the value cell of the symbol.

In shallow binding, setting the variable works by storing a value in the value cell. Creating a new binding works by pushing the old value (belonging to a previous binding) on a stack, and storing the local value in the value cell. Eliminating a binding works by popping the old value off the stack, into the value cell.

We use shallow binding because it has the same results as deep binding, but runs faster, since there is never a need to search for a binding.


Next: , Previous: , Up: Variable Scoping   [Contents][Index]