开发者

elisp: capturing variable from inner function

My lovely function:

(defun f (x)
  (lambda (y) (+ x y)))

Then, I expect this:

(funcall (f 2) 2)

To retu开发者_高级运维rn 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜