A while ago in Lexical Scoping In Emacs Lisp I wrote that Emacs 24 will (finally) introduce lexical binding. Trawling through the EmacsWiki today I came across a page, Dynamic Binding Vs Lexical Binding, that describes the differences between the dynamic binding that Emacs Lisp currently has and the (optional) lexical binding that’s available in Emacs 24.
It’s a good introduction for Elisp programmers who aren’t familiar with lexical binding. It looks at the advantages of dynamic binding and lexical binding and when it’s appropriate to use each. The big win with lexical binding is that it allows us to write closures. There’s an example of a closure on the page but I’m not sure it really makes clear how big a win they can be.
Suppose you need some counters in your program. You’d like to be able to give them an initial value and then increment them by any amount. You could write something like this (given that you have lexical binding):
(defun make-counter (initial-count) (let ((count initial-count)) (lambda (n) (setq count (+ count n)))))
A call to make-counter
will return a counter that you can use to track some count. If you call make-counter
several times, each counter will have a separate count
field so they won’t interfere with each other.
That’s a very simple example, of course, but it’s easy to imagine more complicated examples. The astute reader will notice that the counter is actually a sort object (in the OO sense) that has a single method. It’s easy to provide additional functionality–displaying the count, for example–so that you could have an object with several methods (loosely speaking). This fact is one of the reasons that I don’t use eieio (or CLOS in CL) very much. I get most of the benefits with a simple closure.
In any event, if you are an Elisp programmer and confused about lexical versus dynamic binding, this page is an excellent introduction and well worth a read.