Lexical Scoping In Emacs Lisp

I’ve said before that Emacs Lisp is pretty much like other Lisps but one area where that is not true is in variable scoping. Common Lisp and Scheme both enjoy lexical scoping whereas Emacs Lisp has dynamic scoping. Until you actually use lexical scoping and see what it can do, this seems like an esoteric point that most programmers needn’t worry about. Emacs 24 introduces support for lexical scoping so Elisp programmers can finally make use of this powerful mechanism.

Yoo Box has a long post on lexical scoping and dynamic scoping in Emacs Lisp. It turns out that you can enable lexical scoping for an Elisp file by adding

;;; -*- lexical-binding: t -*-

to the top of the file. If you’re already familiar with lexical scoping that’s just about everything you need to know. If not, then Box has an excellent and detailed explanation of the differences between lexical and dynamic scoping with plenty of examples. The examples are short and seem simple but they require careful study to get their full value.

I really recommend Box’s post if lexical scoping is new to you. A careful reading will pay dividends. For the rest of us, it’s really great that Emacs is finally supporting lexical scoping. It’s still not Common Lisp but it’s a huge improvement.

This entry was posted in Programming and tagged , . Bookmark the permalink.