1

I wan't to implement a closure behavior in Elisp, here is the code:

(setq lexical-binding t)
(setq var 3)
(require 'cl)
(defun foo (n)
  #'(lambda (i)
    (incf n i)))
(defvar bar (foo var))
(funcall bar 1)

what I want get is that every time I run the expr:(funcall bar 1) it will increment the result of the expr by 1. I don't know why it can't work, can someone explain it to me? I found a similar question in the How do I do closures in Emacs Lisp? but I can't understand it. My Emacs version is 24.2.1 which seems support the lexical scoping.

Community
  • 1
  • 1
toolchainX
  • 1,998
  • 3
  • 27
  • 43
  • 1
    Every time you evaluate `(funcall bar 1)` you will get the next number in the sequence (starting with 4). Your code does create a closure. Were you expecting `var` to change value? (verified with Emacs 24.1) – Trey Jackson Jan 02 '13 at 15:16
  • @Trey Jackson I got the error that `setq: Symbol's value as variable is void: n`, it can't work in my Emacs, I don't want the `var` to change, I just want to see How to make the closure work. is it works in your Emacs? – toolchainX Jan 03 '13 at 04:34
  • Yup, the code works as is in my Emacs (24.1), I just cut/paste/evaled it again. – Trey Jackson Jan 03 '13 at 16:17
  • very wired... It just can't work on my Emacs (24.2.1) for windows and for ubuntu. – toolchainX Jan 04 '13 at 08:36

1 Answers1

1

The lexical-binding variable is fairly special, I strongly recommend to never use setq on it. Only define it via a -*- lexical-binding: t -*- in a comment on the first line (and that comment only takes effect after you re-visit the corresponding file).

Stefan
  • 27,908
  • 4
  • 53
  • 82