elisp: capturing variable from inner function

2019-04-08 00:20发布

问题:

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?

回答1:

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.



标签: elisp