2

I know that if I have a variable with a function name, I can call it using funcall, like this

(setq func-ref 'my-func)
(funcall func-ref)

I am wondering if there's a similar functionality for variables (defined with defvar), so that I can set var-ref like this

(setq var-ref 'my-var)

and use it to get the value of my-var and/or update it.

EDIT: I want to use this functionality in a function which takes as argument a reference to a variable that will be changed in the function.

2
  • Just use (setq var-ref 'my-var) and (set my-var 42).
    – Drew
    Commented May 24, 2020 at 19:29
  • You could also look at gv-ref and gv-deref
    – npostavs
    Commented May 25, 2020 at 2:23

2 Answers 2

2

You can use symbol-value to look up dynamically bound variables. The easiest way to ensure that is by using defvar/defconst/defcustom for such variables, that way they'll always be dynamically bound, even with lexical-binding enabled. Plain setq will not do as soon as lexical binding is used and is discouraged for defining variables for that reason.

To change the value, use set instead of setq and give it a symbol.

1

You can eval to recover the value of a variable symbol. To modify it you can use setf:

(setq x 1)
(setq xref 'x)
(eval xref) ;; Returns 1
(setf (symbol-value xref) 2)
(eval xref) ;; Returns 2

The value of x is now 2

setf is the generalized version of setq that lets you place values in arbitrary "places" within an object. For example you can change elements within a list:

(setq x '(1))
(car x) ;; Returns 1
(setf (car x) 2)
(car x) ;; Returns 2
3
  • Does that mean I cannot have pointers (or references to variables)? I don't think your second example can be used in my case where I want to write a function that can change a variable (defined with defvar) whose name is given as an argument to the function.
    – Tohiko
    Commented May 24, 2020 at 16:08
  • Please do not suggest the use of eval unless absolutely necessary.
    – wasamasa
    Commented May 24, 2020 at 16:22
  • @Tohiko You can. I've edited the answer to make it do this.
    – erikstokes
    Commented May 24, 2020 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.