Search code examples
emacselisp

Emacs lisp: create list using quote in local scope(e.g function scope)


My code is like this:

(defun test () "Test."
  (setq lista '(A))
  (push 'B lista)
  (nreverse lista))

(message "%s" (test))  ; Output is (A B)
(message "%s" (test))  ; Output is (B A B)

It seems strange because I expect the result to be

(A B)
(A B)

If I substitute (setq lista '(A)) with (setq lista (list 'A)), I get the result expected. I think the list creating methods cause the difference but I don't know the detail.

My emacs version is GNU Emacs 24.5.1


Solution

  • You're doing this:

    (defvar t1 '(A))
    (defun test ()
      "Test."
      (setq lista t1)
      (push 'B lista)
      (nreverse lista))
    

    You modify a cons cell that's part of the code: after the first call, t1 becomes '(A B).

    Avoid it by using (list) instead of (quote):

    (defun test ()
      "Test."
      (setq lista (list 'A))
      (push 'B lista)
      (nreverse lista))