Search code examples
emacselisplexical-scope

Elisp variable bind to itself


I have elisp code like this:

(setq a nil)
(defun testa (a) (add-to-list a "ABCD"))
(testa 'a)

What I want is to make a list ("ABCD") but since the argument name of the function testa is the same as variable a, the local binding of a in the function is itself, which doesn't bind the value outside of function.

My question is: Is it the feature of elisp that I can't work around if I don't rename the variable outside or is there any neat solution?


Solution

  • This is the intended behavior in elisp. For more information on variable scoping with elisp, the manual has a thorough explanation. This post also does a good job of explaining scoping.

    It is not possible to pass a reference to a variable. It is however possible to pass a function that returns or modifies a globally (or dynamically) scoped variable. It is also possible to have a function that modifies an already known variable.

    Edit: Added more detail.