0

I am reading the Common Lisp Hyperspec and am struggling to understand the concept behind the Special declaration.

Namely, what are the special variables and why would we want them? I gathered that somehow we can change which scope the variable belongs to in the eyes of the compiler by using the special declaration, but the details elude me.

Could someone explain and perhaps give some examples?

MadPhysicist
  • 5,401
  • 11
  • 42
  • 107
  • I don't know if it's fitting, but I've used special variables in a multithreaded application. After writing a standard single-threaded program that uses a global variable to store the current state of a problem, you can then write a multithreaded version that rebinds it locally in each thread to allow each thread to work on the problem independently. It was a relatively easy conversion to multithreaded, but not sure if it's a good design principle, in general. – davypough Apr 15 '19 at 22:57

1 Answers1

3

Special variables are dynamically bound. That means:

(defvar x 10)

(defun test (v) 
  (+ v x)) 

(let ((x 20))
  (test x)) 
; ==> 40

Notice that lexical rules of scoping does not apply. Rather than that it behaves like the very first Lisp. If global variables would not been special the result would be 30. You can introduce hard to find bugs by accidentally declaring a variable special. To avoid this we use *earmuffs*.

Sylwester
  • 47,942
  • 4
  • 47
  • 79