The lexical-binding
settings of the files loaded with load
and require
are not affected by the (buffer-local) lexical-binding
setting of the init file.
Warning:
But, a change of lexical-binding
in the init file can cause errors there.
Example for a change through lexical-binding
t
:
(setq var-a 0)
(defun a ()
(message "a: %s" var-a))
(defun b ()
(let ((var-a 1))
(a)))
Calling (b)
gives 0
with lexical binding and 1
with dynamical binding.
You need a defvar
for var-a
before (defun b...)
the to declare a
as special (i.e., always dynamically bound).
The defvar
can also be indirect through a require
of the package where var-a
already has a defvar
.
You are hard to convince.
Let's have a look.
- We leave no room for speculations. We check the lexical binding directly by effect and not through testing the variable
lexical-binding
. Testing lexical-binding
would give the same result.
- Note that the macro
lexical-p
is expanded during the evaluation of the loaded files.
.emacs
init file:
;;; -*- lexical-binding: t -*-
(defmacro lexical-p ()
"Return non-nil in buffers with lexical binding."
'(let* ((ret t)
(code (lambda ()
ret)))
(let ((ret nil))
(funcall code))))
(message "Load file name: %s, Lexical binding: %s" load-file-name (lexical-p))
(add-to-list 'load-path "/tmp")
(load "loaded.el")
(require 'required)
The load file loaded.el
:
(message "Load file name: %s, Lexical binding: %s" load-file-name (lexical-p))
The library required.el
:
(message "Load file name: %s, Lexical binding: %s" load-file-name (lexical-p))
(provide 'required)
The messages at start of emacs
:
Load file name: /home/naehring/.emacs, Lexical binding: t
Loading /tmp/loaded.el (source)...
Load file name: /tmp/loaded.el, Lexical binding: nil
Loading /tmp/loaded.el (source)...done
Load file name: /tmp/required.el, Lexical binding: nil
lexical-binding
is buffer-local. The most common way of setting it is as a file-local variable. In any case, you should read (elisp)Using Lexical Binding andC-h v lexical-binding
.