common-lisp 全局特殊变量在任何地方都是特殊的
示例
因此,这些变量将使用动态绑定。
(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)