6

My lovely function:

(defun f (x)
  (lambda (y) (+ x y)))

Then, I expect this:

(funcall (f 2) 2)

To return 4. But alas, I got this instead:

Debugger entered--Lisp error: (void-variable x)

So how can I capture variable from inner function?

Ron
  • 6,768
  • 11
  • 37
  • 40
  • 3
    As of Emacs 24, there is another workaround for the dynamic-scoping "bug": you can put `;; -*- lexical-binding: t -*-` at the top of the file to enable lexical scoping. If you do this, the above code runs as expected. – Patrick Brinich-Langlois Oct 02 '12 at 17:05

1 Answers1

8

You've been bitten by elisp's dynamic scoping. The x in the lambda refers to the variable x that is in scope when the lambda is called (and since in this case there is no x in scope when you call it, you get an error), not to the x which is in scope when you create the lambda.

Some ways of simulating lexical closures in elisp are explained on this page on the EmacsWiki.

sepp2k
  • 353,842
  • 52
  • 662
  • 667