The less-familiar parts of Lisp for beginners — special

We’ve hinted a few times at special variables, but I’ll put it here in one spot to make it easier to find.  The special declaration is used, for instance in declaim or declare, to indicate that a variable should have dynamic binding.

The most important thing to realize about a dynamic variable is that it behaves as if implemented by a push-down stack.  Declaring a new local variable with the same name, for instance with let, creates a new dynamic extent that is visible in any called functions.  Modifications to the value of the variable are visible until the dynamic extent is exited, at which point the next enclosing extent becomes the current one.

It is a common convention that special variables have variable names that begin and end in an asterisk, but this is not typically enforced by the implementation.  Variables created with defvar or defparameter are always dynamic.

Here’s some simple code to demonstrate the behaviour:
special.lisp

(defparameter *myvar* 10)

(defun printvar ()
  (format t "*myvar*= ~D~%" *myvar*))

(defun incvar ()
  (incf *myvar*))

(defun demonstrate ()
  (format t "Outermost dynamic extent:~%")
  (printvar)
  (format t "Incrementing the value~%")
  (incvar)
  (printvar)
  (format t "Creating a new dynamic extent with value 15:~%")
  (let ((*myvar* 15))
    (printvar)
    (format t "Incrementing the value~%")
    (incvar)
    (printvar))
  (format t "Exiting this new dynamic extent~%")
  (printvar))
          

with output:
*slime-repl sbcl*
CL-USER> (demonstrate)
Outermost dynamic extent:
*myvar*= 10
Incrementing the value
*myvar*= 11
Creating a new dynamic extent with value 15:
*myvar*= 15
Incrementing the value
*myvar*= 16
Exiting this new dynamic extent
*myvar*= 11
NIL

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.