7

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
  • 7,588
  • 11
  • 38
  • 42
  • 4
    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

9

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
  • 363,768
  • 54
  • 674
  • 675