next up previous
Next: Scoping Rules Up: Variable Operations Previous: Defining Variables

Global and 'Local' Variables

We have talked of three ways of bringing variables into existence - defvar defconst setq. The variables born thus will be in the global namespace - exactly like global variables in C. This means even if your first setq on a variable is in the body of a defun, once the function gets executed the variable, and the set value will be `visible' to all.

It is possible to create local variables that exist temporarily-only until a certain part of the program finishes. In fact, such temporary local variables get created automatically for functions with arguments. The local variables are assigned values from the function invocation, and after the function returns their old values are restored. If a variable does not exist outside the function, but is used as a function argument, once the function returns, it will remain undefined. In other words, the arguments of a function get new bindings and the previous values are shadowed.

It is possible to give variables a new binding at arbitrary point in your program by using the let special form. The syntax of a let form is something like this:

(let ((variable-1 10)
      (variable-2 "abcd"))
  (...))

The above let form provides new binding to two variables. The new bindings last until execution exits from the let form. let forms can be nested; however, there is a limit on the maximum number of nested bindings an individual variable can have. This limit is specified by the value of max-specpdl-size.

setq alters the value of the inner-most binding. If there are no local bindings, then it alters the global value. This rule is called ``dynamic scoping''. We examine the variable scoping rules in a little more detail in the next section.


next up previous
Next: Scoping Rules Up: Variable Operations Previous: Defining Variables
Sriram Karra
2005-01-06