Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Syntax and Evaluation

Symbols, Variables and Scope

Learn what symbols are, how let, setf, defvar and defparameter create variables, the difference between lexical and dynamic (special) binding, and how packages organize names.

Variables in Common Lisp work a little differently from most languages because the name of a variable is a symbol, an object in its own right. This lesson explains symbols and packages briefly, then covers the ways to create variables (let, let*, defparameter, defvar, defconstant), how setf changes them, and the key difference between lexical and dynamic scope.

Symbols

A symbol is a named object. It has a name (a string), and it can carry a value, a function definition, and a property list, all at once and separately.

LISP
(symbol-name 'hello)     ; => "HELLO"
(symbolp 'hello)         ; => T
(eq 'hello 'HELLO)       ; => T  (the reader upcases both)

Symbols are unique per name inside a package: every hello you type is the same object, so comparing symbols with eq is fast. That is why symbols are used as names, tags and enumeration values:

LISP
(defun traffic-action (colour)
  (case colour
    (red    "stop")
    (yellow "slow")
    (green  "go")))

(traffic-action 'green)   ; => "go"

Keywords

A symbol starting with a colon is a keyword. Keywords evaluate to themselves and are always in the keyword package, so they are perfect for options and tags:

LISP
:name       ; => :NAME
(eq :a :a)  ; => T
(keywordp :a) ; => T

Packages in one minute

A package is a namespace for symbols. The REPL starts in COMMON-LISP-USER (CL-USER). car is really common-lisp:car; you can write the prefix explicitly: cl:car. Your own symbols live in your own package, which is what prevents name collisions between libraries. Define one with defpackage and enter it with in-package (details in the tooling chapter).

LISP
(defpackage :my-app (:use :cl))
(in-package :my-app)

Use package:symbol for an exported symbol and package::symbol for an internal one. Within files you will almost always see (in-package ...) on the first line.

Global variables: defparameter and defvar

LISP
(defparameter *greeting* "Hello")
(defvar *counter* 0)

Both create a global (special) variable. By convention such names are wrapped in asterisks, called earmuffs, so you can see at a glance that a variable is special.

The difference:

Form If the variable already has a value
defparameter Resets it to the new value each time it is evaluated
defvar Leaves the old value alone (only sets if unbound)

Use defparameter for settings you want to reload from a file; use defvar for state that should survive a reload, such as a cache.

LISP
(defvar *cache* (make-hash-table))   ; reloading this file will NOT wipe the cache
(defparameter *debug* nil)           ; reloading resets it

defconstant is for values that never change ((defconstant +max-size+ 100)); constants wear plus signs by convention. Redefining a constant to a non-eql value is an error, so strings and lists are awkward constants. Use defparameter for those.

Local variables: let and let*

let creates variables that exist only inside its body:

LISP
(let ((x 10)
      (y 20))
  (+ x y))        ; => 30
;; x and y no longer exist here

All the init forms in a let are evaluated before any variable is bound, so they cannot see each other:

LISP
(let ((x 1)
      (y (+ x 1)))   ; ERROR: this x is not the new x
  y)

let* binds sequentially, so later forms see earlier variables:

LISP
(let* ((x 1)
       (y (+ x 1))
       (z (* y 10)))
  (list x y z))     ; => (1 2 20)

Here are both running on the Mini-Lisp stand-in (a JavaScript interpreter, not SBCL), including shadowing and setf:

JS Mini-Lisp: let, let* and setf

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The inner let makes a new variable that shadows the outer one; the outer total is untouched.

Changing values with setf

setf assigns to a "place". The simplest place is a variable:

LISP
(defparameter *score* 0)
(setf *score* 10)        ; => 10
(setf a 1 b 2)           ; sets two variables, returns 2
(incf *score* 5)         ; => 15
(setf (car list) 'new)   ; a place can be part of a data structure
(setf (gethash :k table) 42)
(setf (aref v 0) 99)

The idea of places (variables, conses, array cells, hash entries, struct slots) all assigned the same way is a famous Common Lisp convenience. Setting an undefined variable at the REPL with setf works in SBCL but prints a warning; always define it with defparameter or let first.

Lexical versus dynamic scope

This is the most important idea in the lesson.

Lexical scope (the default for let and function parameters): a variable can be seen only by code that is written inside the form that creates it. You can tell by reading the source.

Dynamic scope (variables created with defvar or defparameter): a let of such a variable changes its value for everything called during the let, even code written elsewhere. It lasts for the dynamic extent (the time) of the form.

LISP
(defparameter *indent* 0)

(defun show (text)
  (format t "~a~a~%" (make-string *indent* :initial-element #\Space) text))

(defun nested ()
  (show "outer")
  (let ((*indent* 4))      ; rebinds the SPECIAL variable
    (show "inner")         ; show sees *indent* = 4
    (show "inner again"))
  (show "outer again"))    ; back to 0 automatically

show does not take an indentation parameter, yet it sees the new value because *indent* is special. When the let ends, the old value returns, even if an error unwinds the stack. This makes special variables ideal for configuration that flows through many calls: output streams (*standard-output*), the current package (*package*), print settings (*print-base*), and so on.

LISP
(let ((*print-base* 2))
  (print 10))        ; prints 1010

(with-output-to-string (*standard-output*)
  (print "captured"))   ; rebinding *standard-output* captures printing

Here is a stand-in that models a dynamic variable with an explicit stack. This is plain JavaScript showing the idea, not real Lisp:

JS Stand-in: dynamic binding

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Lexical variables and closures

Lexical variables can be captured by functions that outlive the let, giving closures. That deserves its own lesson: Closures and Lexical Scope.

Useful predicates and functions

LISP
(boundp '*score*)        ; => T if the symbol has a global value
(fboundp 'car)           ; => T if it names a function
(makunbound '*score*)    ; remove the value
(symbol-value '*score*)  ; get the value of a symbol at runtime

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between defvar and defparameter?

    defvar only initializes an unbound variable, so reloading a file does not reset it; defparameter always sets it.
  2. 2. What does (let* ((x 1) (y (+ x 1))) y) return?

    let* binds sequentially, so y sees x = 1 and becomes 2.
  3. 3. Why are special variables named like indent?

    Earmuffs are only a convention, but they warn readers that rebinding affects all called code.
  4. 4. A let rebinds a special variable. Who sees the new value?

    Dynamic binding applies for the dynamic extent of the form.
  5. 5. Which is a keyword symbol?

    Keywords start with a colon and evaluate to themselves.

Summary

  • Symbols are unique named objects; keywords (:name) evaluate to themselves.
  • defparameter and defvar create global special variables; use earmuffs. defconstant for true constants.
  • let binds in parallel, let* sequentially; setf assigns to any place.
  • Lexical variables are visible only in their source region; special variables are rebound for the dynamic extent of a let.
  • Packages are namespaces for symbols.

Next: Characters and Strings