Mini Tutorial Special Variables
A global (and special) variable is created with defvar or defparameter:
(defvar *global-var-1*)
(defvar *global-var-2* 42 "With an initial value if it doesn't already have one and a docstring.")
(defparameter *global-var-3* 33 "Defparameter always assigns the value to the variables.")
To use them, just reference them in code:
(defun g () (list *global-var-1* *global-var-2* *global-var-3*))
(defun f ()
(setf *global-var-1* 1) ; set its value
(print *global-var-2*) ; get its value
(let ((*global-var-3* 0)) ; dynamically bind it (shadowing the global for the TIME being):
(g)))
(f)
;; prints: 42
;; returns: (1 42 0)
(let ((*global-var-2* 22))
(f))
;; prints: 22
;; returns: (1 22 0)
But you can also have non-global dynamic variables:
(defun h ()
(declare (special zz))
(list zz))
(h)
;; error: Unbound variable: zz
(defun i ()
(let ((zz 42))
(declare (special zz))
(h)))
(i)
;; returns: (42)
(let ((zz 33))
(declare (special zz))
(h))
;; returns: (33)
defvar or defparameter have both compilation-time effects and load-time/execution effects. For their compilation-time effects to be visible, they must be written before the functions that use the variables, otherwise the compiler will signal a warning.
Categories: Online Tutorial Keywords: special variable dynamic binding