Next: Selecting Lisp Dialect, Previous: ダイナミックバインディング, Up: 変数のバインディングのスコーピングルール [Contents][Index]
Dynamic 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コーディング規約).
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 グローバル変数の定義), or defcustom
(see カスタマイゼーション変数の定義). 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.
そうすればプログラム内のどこか別の場所で、それが何に影響するか確信をもって変数をバインドすることができます。その変数にどこで出会っても、(たとえば変数の定義がEmacsにロードされていればC-h vコマンドを通じて)定義を参照するのが簡単になります。Name Help in The GNU Emacs Manualを参照してください。
たとえばcase-fold-search
のようなカスタマイズ可能な変数にたいしてローカルバインディングを使用するのは一般的です:
(defun search-for-abc () "Search for the string \"abc\", ignoring case differences." (let ((case-fold-search t)) (re-search-forward "abc")))