[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
TIL: buffer-local variables are used over let-bound variables when using
From: |
Rodrigo Morales |
Subject: |
TIL: buffer-local variables are used over let-bound variables when using with-current-buffer in let |
Date: |
Sun, 22 Oct 2023 05:45:11 +0000 |
TIL: buffer-local variables are used over let-bound variables when using
with-current-buffer in let
Let's suppose we have a directory =/tmp/foo=
#+BEGIN_SRC elisp
(dired-create-directory "/tmp/foo")
#+END_SRC
Now, let's suppose we create a buffer while =/tmp/foo= is
=default-directory=.
#+BEGIN_SRC elisp
(let ((default-directory "/tmp/foo"))
(get-buffer-create "*foo*"))
#+END_SRC
Now, let's suppose we have another directory =/tmp/bar=.
#+BEGIN_SRC elisp
(dired-create-directory "/tmp/bar")
#+END_SRC
The result of evaluation of the following sexp is =/tmp/foo=.
#+HEADER: :results value
#+BEGIN_SRC elisp
(let ((default-directory "/tmp/bar"))
(with-current-buffer (get-buffer "*foo*")
default-directory))
#+END_SRC
#+RESULTS:
#+begin_example
/tmp/foo
#+end_example
Some users would expect for the result to be =/tmp/bar= because
=default-directory= has been modified in =let=. However that's not the case
because when we change to buffer =*foo*=, the variable =default-directory==
has another value.
I think this scenario arises when a variable is buffer-local and that
variable is modified in a =let= form and =with-current-buffer= is used
inside the =let= form. In such a case, the buffer-local value would be used
instead.
- TIL: buffer-local variables are used over let-bound variables when using with-current-buffer in let,
Rodrigo Morales <=