Search code examples
emacselisp

Why is lexical binding not working in this example in emacs?


I copy-pasted this example from the emacs wiki: https://www.emacswiki.org/emacs/DynamicBindingVsLexicalBinding#toc2

The wiki says that the printed thing should be 1, but for me it prints 2, indicating that lexical binding doesn't work. Does anyone have a clue why that might be?

I'm on Emacs v26. Debian.

Here is what is literally in my buffer. I am evaluating it with M-x eval-buffer.

;; -*- lexical-binding: t;-*-

(let ((a 1))                            ; binding (1)
  (let ((f (lambda () (print a))))
    (let ((a 2))                        ; binding (2)
      (funcall f))))

I would appreciate your help.


Solution

  • You set lexical-binding as a file variable. That gets set when the file is opened, so if you just add the text to the file without closing it and reopening it, the value of lexical-binding will still be nil (do C-h v lexical-binding RET and see for yourself). So you are using dynamic binding and you get 2 for the value.

    If you close and reopen the file, the file variable will be set (check it!) and when you evaluate the form, you will get 1.