Search code examples
variableslispelisp

How to access the value of a variable inside a list?


I'm a newbie in ELisp and I can't set a variable value to access later. I read the documentation on accessing variable values and tried the answers in this thread, but I am still getting Wrong type argument: char-or-string-p.

Here is the output of my *scratch* Emacs buffer, which runs the code and inserts it after any side effects:

(defvar my-var "var"  "Some documentation")
my-var

my-var
"var"

(symbol-value 'my-var)
"var"

I can iterate on a list made from the value as a literal:

(dolist (v '("var"))
  (insert v))
varnil

But each of these attempts to iterate on the value as a variable fail with the same error Wrong type argument: char-or-string-p:

(dolist (v '(my-var))
  (insert v))

(dolist (v '((format "%S" my-var)))
  (insert v))

(dolist (v '((symbol-value 'my-var)))
  (insert v))

How can I iterate on a list made from values of variables?


Solution

  • You need to either evaluate your variables:

    (dolist (v (list my-var))
      (insert v))
    

    or get the values yourself:

    (dolist (v (list 'my-var))
      (insert (symbol-value v)))
    

    If you want to mix variables and literals, then use the first approach:

    (defvar my-var "var"  "Some documentation")
    
    (dolist (d (list my-var
                     "other-var"))
      (insert d))
    

    See also When to use ' (or quote) in Lisp?