If we define a function something like
(defun foo(x)
(setf x somevalue))
Is x
defined as a local variable or global? using setf/
Actually, x
is local to the function, so setf
or setq
ing it only changes the local variable x
.
To answer the second part of your question, there is another way to define a local variable other than let:
(funcall (lambda (var1 var2...)
... use var1 var2 ...)-
val1 val2 ...)
In fact, defun
could be implemented as
`(setf (symbol-function ,name) (lambda ,args ,@body))
though all the implementations I've checked do more than that.
Also, the symbol-function
place allows you to do this:
(setf (symbol-function '+) (function -))
though that's generally a bad idea.
What's happening there is that x
is local to the scope that contains the defun
. It's not a global variable. What you're doing with that defun
is creating a closure that "captures" all the lexically-scoped (not created with defvar
/defparameter
) variables in the surrounding scopes and holds on to them for the future. If you want to inspect the value of x
, add another function
(defun get-x () x)
inside the let
. To put it another way, x
is local to the let
that the function is in. The situation you've provided is similar to:
(let ((x 3))
(print x)
(let ((y 7))
(print (list x y))
(setf x y))
(print x))
except the inner let
is replaced by a defun
(which is a lambda
).