title: Dynamic and Lexical variables in Common Lisp
body: <p>I am reading the book 'Practical Common Lisp' by Peter Seibel.</p>
  <p>In Chapter 6, &quot;Variables&quot; sections
  &quot;Lexical Variables and Closures&quot; and &quot;Dynamic, a.k.a. Special, Variables&quot;.
  <a href="http://www.gigamonkeys.com/book/variables.html" rel="nofollow noreferrer">http://www.gigamonkeys.com/book/variables.html</a></p>
  <p>My problem is that the examples in both sections show how (let ...) can shadow global variables and doesn't really tell the difference between the Dynamic and Lexical vars.</p>
  <p>I understand how closures work but I don't really get whats so special about let in this example:</p>
  <pre><code>(defvar *x* 10)
  
  (defun foo ()
    (format t &quot;Before assignment~18tX: ~d~%&quot; *x*)
    (setf *x* (+ 1 *x*))
    (format t &quot;After assignment~18tX: ~d~%&quot; *x*))
  
  
  (defun bar ()
    (foo)
    (let ((*x* 20)) (foo))
    (foo))
  
  
  CL-USER&gt; (foo)
  Before assignment X: 10
  After assignment  X: 11
  NIL
  
  
  CL-USER&gt; (bar)
  Before assignment X: 11
  After assignment  X: 12
  Before assignment X: 20
  After assignment  X: 21
  Before assignment X: 12
  After assignment  X: 13
  NIL
  </code></pre>
  <p>I feel like there is nothing special is going on here. The outer <em>foo</em> in <em>bar</em> increments the global <em>x</em>, and <em>foo</em> surrounded by <em>let</em> in <em>bar</em> increments the shadowed <em>x</em>. What's the big deal? I don't see how is this supposed to explain the difference between lexical and dynamic variables. Yet the book continues like this:</p>
  <blockquote>
  <p>So how does this work? How does LET
  know that when it binds <em>x</em> it's
  supposed to create a dynamic binding
  rather than a normal lexical binding?
  It knows because the name has been
  declared special.12 The name of every
  variable defined with DEFVAR and
  DEFPARAMETER is automatically declared
  globally special.</p>
  </blockquote>
  <p>What would happen if <em>let</em> would bind <em>x</em> using <strong>&quot;normal lexical binding&quot;</strong>? All in all, what are the differences between dynamic and lexical binding and how is this example special regarding dynamic binding?</p>