In portable Common Lisp there is no explicit concept of "pointer" and all parameters are passed by value. To be able pass a function the ability to modify a variable you need to provide a way to reach the variable.
If the variable is a global then you can use the name of the variable (a symbol
) and then use symbol-value
to read/write the variable:
(defvar *test1* 42)
(defun inctest (varname)
(incf (symbol-value varname)))
(inctest '*test1*) ;; Note we're passing the NAME of the variable
if instead the variable is local you could for example provide a closure that when called without parameters returns the current value and that when called with a parameter instead it will set the new value of the variable:
(defun inctest (accessor)
(funcall accessor (1+ (funcall accessor))))
(let ((x 42))
(inctest (lambda (&optional (value nil value-passed))
(if value-passed
(setf x value)
x)))
(print x))
You can also write a small helper for building an accessor:
(defmacro accessor (name)
(let ((value (gensym))
(value-passed (gensym)))
`(lambda (&optional (,value nil ,value-passed))
(if ,value-passed
(setf ,name ,value)
,name))))
after which the code becomes
(let ((x 42))
(inctest (accessor x))
(print x))
(defun foo (x) (setf x 'foo))
would change a variable that it was called with. @OpenLearner's confusion is about the difference between mutating a variable and mutating an object. – Tobiasvoid foo(string& x) { x = "foo"; }
, and it will change the variable of the caller. In Common Lisp, this applies: lispworks.com/documentation/lw50/CLHS/Body/03_ac.htm. Note in the first sentence: "the corresponding value". – Tobias(defun foo (x) (setf x 'foo))
would change a variable that it was called with." The point that you're making is right, but I disagree with this phrasing, only because the function named byfoo
is never called with a variable; it's called with an object. In(foo a)
, becausefoo
is a function,
a` is _evaluated and its value is passed tofoo
.setf
, on the other hand, because it is a macro can be called with variables (and, in general, places), and so can modify a variable (i.e., the value of the binding). – Avery