I’m learning Common Lisp, using CCL. I get a warning when I use a global variable locally. Why does CCL provide this functionality? What is the purpose of this?
(setf n 75)
;;;This function works, but gets a warning about
;;;n being an undeclared free variable.
(defun use-global ()
(write n)
)
;;;This function works without warnings.
(defun global-to-local (x)
(write x)
)
(use-global)
(global-to-local n)
Setf
and setq
do not introduce new variables, they modify existing ones.
In order to define something like global variables, use defvar
or defparameter
. These are conventionally written with a leading and ending *
, and they are automatically declared globally special. This means that whenever you re-bind them, this binding is in effect for the entire call stack above it, whatever functions you call from there etc..
In your example, the toplevel setf
did not do that, so when compiling the function use-global
, the compiler does not see that n
is meant as such and issues the warning. In correct and idiomatic Common Lisp code, this warning should generally be treated as an error, since it then indicates a misspelling or typo.