Defining Global Variables in Lisp

As the player calls the functions that make up our game, the program will need to track the small and big limits. In order to do this, we’ll need to create two global variables called *small* and *big*.

Defining the small and big Variables

A variable that is defined globally in Lisp is called a top-level definition. We can create new top-level definitions with the defparameter function:

> (defparameter *small* 1)
*SMALL*
> (defparameter *big* 100)
*BIG*

The function name defparameter is a bit confusing, since it doesn’t really have anything to do with parameters. What it does is let you define a global variable.

The first argument we send to defparameter is the name of the new variable. The asterisks surrounding the names *big* and *small*—affectionately called earmuffs—are completely arbitrary and optional. Lisp sees the asterisks as part of the variable names and ignores them. Lispers like to mark all their global variables in this way as a convention, to make them easy to distinguish from local variables, which are discussed later in this chapter.

Note

Although earmuffs may be “optional” in a strictly technical sense, I suggest that you use them. I cannot vouch for your safety if you ever post any code to a Common Lisp newsgroup and your global variables are missing their earmuffs.

An Alternative Global Variable Definition Function

When you set the value of a global variable using defparameter, any value previously stored in the variable will be overwritten:

> (defparameter *foo* 5)
FOO
> *foo*
5
> (defparameter *foo* 6)
FOO
> *foo*
6

As you can see, when we redefine the variable *foo*, its value changes.

Another command that you can use for declaring global variables, called defvar, won’t overwrite previous values of a global variable:

> (defvar *foo* 5)
FOO
> *foo*
5
> (defvar *foo* 6)
FOO
> *foo*
5

Some Lispers prefer to use defvar instead of defparameter when defining global variables. In this book, however, we’ll be using defparameter exclusively.

Note

When you read about Lisp in other places, you may also see programmers using the term dynamic variable or special variable when referring to a global variable in Common Lisp. This is because global variables in Common Lisp have some special abilities, which we’ll be discussing in future chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.134.133