From: Chip Salzenberg
Subject: The answer: Undeclared free variables are special
Date:
Message-ID: <256C52AF.135@ateng.com>
Thanks to many who responded to my earlier query about free variables. The
question was, what is the output of this Common Lisp code:
(setq *parrot* "live") ;; no previous declaration of *parrot*
(defun cleese ()
(let ((*parrot* "dead"))
(declare (special *parrot*))
(palin)
*parrot*))
(defun palin ()
(print *parrot*)) ;; no declaration in scope
(cleese)
The answer:
"dead"
"dead"
Quoting page 55 of Common Lisp the Language:
There are actually two kinds of variables in Common Lisp, called
_lexical_ (or _static_) variables and _special_ (or _dynamic_)
variables.
Thus we have defined that there is no such thing as a "global" variable --
there are only lexical and special variables. Continuing:
The general rule is that if the symbol occurs textually within a
program construct that creates a binding for a variable of the same
name, then the reference is to the variable specified by the
binding; if no such program construct textually contains the
reference, then it is taken to refer to the special variable of that
name. ^^^^^^^ ^^^^^^^^
Now, we can all tell from the above code that *parrot* is not a lexical
variable. It therefore must be special. And since (cleese) created the
special binding of *parrot* to "dead", that's the binding (palin) sees.
This construct causes warnings from some compilers, since a reference to a
non-defvar'd free variable might be a misspelling. But it's legal.
Thanks in particular to Barry Margolin and Tim Moore for helpful answers.
--
You may redistribute this article only to those who may freely do likewise.
Chip Salzenberg at A T Engineering; <ยทยทยทยท@ateng.com> or <uunet!ateng!chip>
"Did I ever tell you the Jim Gladding story about the binoculars?"