Next: Selecting Lisp Dialect, Previous: Dynamic Binding, Up: Scoping Rules for Variable Bindings [Contents][Index]
12.10.3 Proper Use of Dynamic BindingDynamic binding is a powerful feature, as it allows programs to refer to variables that are not defined within their local textual scope. However, if used without restraint, this can also make programs hard to understand.
First, choose the variable’s name to avoid name conflicts (see Emacs Lisp Coding Conventions).
defvar
form without an initial value, and never assign to it unless it is already bound. This way, any attempt to refer to the variable when unbound will result in a void-variable
error.defvar
, defconst
(see Defining Global Variables), or defcustom
(see Defining Customization Variables). Usually, the definition should be at top-level in an Emacs Lisp file. As far as possible, it should include a documentation string which explains the meaning and purpose of the variable.
Then you can bind the variable anywhere in a program, knowing reliably what the effect will be. Wherever you encounter the variable, it will be easy to refer back to the definition, e.g., via the C-h v command (provided the variable definition has been loaded into Emacs). See Name Help in The GNU Emacs Manual.
For example, it is common to use local bindings for customizable variables like case-fold-search
:
(defun search-for-abc () "Search for the string \"abc\", ignoring case differences." (let ((case-fold-search t)) (re-search-forward "abc")))
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4