全局特殊变量在各处都很特殊
因此这些变量将使用动态绑定。
(defparameter count 0)
;; All uses of count will refer to this one
(defun handle-number (number)
(incf count)
(format t "~&~d~%" number))
(dotimes (count 4)
;; count is shadowed, but still special
(handle-number count))
(format t "~&Calls: ~d~%" count)
==>
0
2
Calls: 0
为特殊变量提供不同的名称以避免此问题:
(defparameter *count* 0)
(defun handle-number (number)
(incf *count*)
(format t "~&~d~%" number))
(dotimes (count 4)
(handle-number count))
(format t "~&Calls: ~d~%" *count*)
==>
0
1
2
3
Calls: 4
注 1:在某个范围内不可能使全局变量非特殊。没有声明来制作变量词法。
注 2:可以使用 special
声明在本地上下文中声明一个特殊变量。如果该变量没有全局特殊声明,则声明仅在本地并且可以被遮蔽。
(defun bar ()
(declare (special a))
a) ; value of A is looked up from the dynamic binding
(defun foo ()
(let ((a 42)) ; <- this variable A is special and
; dynamically bound
(declare (special a))
(list (bar)
(let ((a 0)) ; <- this variable A is lexical
(bar)))))
> (foo)
(42 42)