Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elisp: capturing variable from inner function

Tags:

elisp

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?

like image 742
Ron Avatar asked Feb 16 '11 17:02

Ron


1 Answers

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.

like image 121
sepp2k Avatar answered Oct 18 '22 20:10

sepp2k