0

Today I discovered that if you re-evaluate a defun using eval-defun (C-M-x) in a buffer with lexical-binding set to t, the defun is recreated as an ordinary lambda, not a closure.

For example, after you evaluate this file:

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

(defun foo (x) (lambda (y) (+ x y)))

Then (symbol-function 'foo) returns

(closure (t) (x) (function (lambda (y) (+ x y))))

But if you put point in the body of the function, press C-M-x, and evaluate (symbol-function 'foo) again, you get:

(lambda (x) (function (lambda (y) (+ x y))))

Certainly not the same thing, and in fact it throws a void-variable error when you call the returned function, if x is not globally bound.

Is this the intended behavior? Do I just need to remember not to use eval-defun but rather eval-buffer whenever I modify a function in a file where lexical-binding is t?

I'm using Emacs 25.0.50.2.

3
  • Do I just need to remember not to use eval-defun but rather eval-buffer whenever I modify a function in a file where lexical-binding is t? Yes, it seems so.
    – Drew
    May 22, 2015 at 21:31
  • @Sean: This would be a bug. I can't reproduce it here, tho. Did you add the -*- lexical-binding: t; -*- cookie after you opened the file, by any chance?
    – Stefan
    May 22, 2015 at 22:16
  • @Stefan: Yes I did, and that indeed makes the difference. If you put your response in an answer, I'll accept it.
    – Sean
    May 23, 2015 at 17:54

1 Answer 1

2

The -*- lexical-binding: t; -*- only takes effect when you open the file. So after adding it, you need to re-open the file otherwise your buffer is still in dynamic-binding mode.

2
  • This is a gotcha, which should be pointed out in the doc.
    – Drew
    May 29, 2015 at 21:48
  • It applies to all file-local variables. So if it needs to be documented it's in the section about file-local variables, rather than the section about lexical-binding or about eval-defun.
    – Stefan
    May 29, 2015 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.