toolchainX
toolchainX

Reputation: 2057

why this code couldn't work with Emacs-lisp

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.

Upvotes: 1

Views: 80

Answers (1)

Stefan
Stefan

Reputation: 28541

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).

Upvotes: 1

Related Questions