Next: , Previous: , Up: Variables   [Contents][Index]

12.10 Scoping Rules for Variable Bindings

When you create a local binding for a variable, that binding takes effect only within a limited portion of the program (see Local Variables). This section describes exactly what this means.

Each local binding has a certain scope and extent. Scope refers to where in the textual source code the binding can be accessed. Extent refers to when, as the program is executing, the binding exists.

For historical reasons, there are two dialects of Emacs Lisp, selected via the lexical-binding buffer-local variable. In the modern Emacs Lisp dialect, local bindings are lexical by default. A lexical binding has lexical scope, meaning that any reference to the variable must be located textually within the binding construct11. It also has indefinite extent, meaning that under some circumstances the binding can live on even after the binding construct has finished executing, by means of objects called closures. Lexical scoping is also commonly called static scoping.

Local bindings can also be dynamic, which they always are in the old Emacs Lisp dialect and optionally in the modern dialect. A dynamic binding has dynamic scope, meaning that any part of the program can potentially access the variable binding. It also has dynamic extent, meaning that the binding lasts only while the binding construct (such as the body of a let form) is being executed.

The old dynamic-only Emacs Lisp dialect is still the default in code loaded or evaluated from Lisp files that lack a dialect declaration. Eventually the modern dialect will be made the default. All Lisp files should declare the dialect used to ensure that they keep working correctly in the future.

The following subsections describe lexical binding and dynamic binding in greater detail, and how to enable lexical binding in Emacs Lisp programs.


Footnotes

(11)

With some exceptions; for instance, a lexical binding can also be accessed from the Lisp debugger.

Next: Buffer-Local Variables, Previous: Running a function when a variable is changed., Up: Variables   [Contents][Index]