elisp: capturing variable from inner function

你离开我真会死。 提交于 2019-12-12 08:51:41

问题


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.



来源:https://stackoverflow.com/questions/5020009/elisp-capturing-variable-from-inner-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!