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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With