Search code examples
lispcommon-lisp

How to mutate global variable passed to and mutated inside function?


I'm wondering how to permanently alter the value of a global variable from inside a function, without using the variable's name inside the function, i.e.:

(defvar *test1* 5)
(defun inctest (x) (incf x))
(inctest *test1*) ;after it runs, *test1* is still 5, not 6

According to this:

if the object passed to a function is mutable and you change it in the function, the changes will be visible to the caller since both the caller and the callee will be referencing the same object.

Is that not what I'm doing above?


Solution

  • If you want inctest to be a function, pass it the name of the global variable.

    (defun inctest (x) (incf (symbol-value x)))
    (inctest '*test1*)