Next: , Previous: , Up: Welcome to Lisp   [Contents][Index]


16.4.10 Variables

One of the most frequently used operators in Common Lisp is let, which allows you to introduce new local variables:

> (let ((x 1) (y 2))
    (+ x y))
3

A let expression has two parts:

  1. a list of instructions for creating variables, each of the form ‘(variable expression)’. Each variable will initially be set to the value of the corresponding expression.
  2. a body of expressions, which are evaluated in order. The value of the last expression is returned as the value of the let‘.

Here is an example of a more selective version of askem written using let:

(defun ask-number ()
  (format t "Please enter a number. ")
  (let ((val (read)))
    (if (numberp val)
        val
        (ask-number))))

This function creates a variable val to hold the object returned by read. Because it has a handle on this object, the function can look at what you entered before deciding whether or not to return it. numberp is a predicate that tests whether its argument is a number.

If the value entered by the user is not a number, ask-number calls itself. The result is a function that insists on getting a number.

Variables like those we have seen so far are called local variables. They are only valid within a certain context. There is another kind of variable, called a global variable, that can be visible everywhere.22

You can create a global variable by giving a symbol and a value to defparameter.

> (defparameter *glob* 99)
*GLOB*

Such a variable will then be accessible everywhere, except in expressions that create a new local variable with the same name. To avoid the possibility of this happening by accident, it’s conventional to give global variables names that begin and end with asterisks. The name of the variable we just created would be pronounced “star-glob-star”.

You can also define global constants by calling defconstant:

(defconstant limit (+ *glob* 1))

There is no need to give constants distinctive names because it will cause an error if anyone uses the same name for a variable. If you want to check whether some symbol is the name of a global variable or constant, use boundp:

> (boundp ’*glob*)
T

Footnotes

(22)

The real distinction here is between lexical and special variables. More in Chapter 6.


Next: Assignment, Previous: Input and Output, Up: Welcome to Lisp   [Contents][Index]