Node:Looping with while, Next:Loop Example, Previous:while, Up:while
while
So long as the true-or-false-test of the while
expression
returns a true value when it is evaluated, the body is repeatedly
evaluated. This process is called a loop since the Lisp interpreter
repeats the same thing again and again, like an airplane doing a loop.
When the result of evaluating the true-or-false-test is false, the
Lisp interpreter does not evaluate the rest of the while
expression and `exits the loop'.
Clearly, if the value returned by evaluating the first argument to
while
is always true, the body following will be evaluated
again and again ... and again ... forever. Conversely, if the
value returned is never true, the expressions in the body will never
be evaluated. The craft of writing a while
loop consists of
choosing a mechanism such that the true-or-false-test returns true
just the number of times that you want the subsequent expressions to
be evaluated, and then have the test return false.
The value returned by evaluating a while
is the value of the
true-or-false-test. An interesting consequence of this is that a
while
loop that evaluates without error will return nil
or false regardless of whether it has looped 1 or 100 times or none at
all. A while
expression that evaluates successfully never
returns a true value! What this means is that while
is always
evaluated for its side effects, which is to say, the consequences of
evaluating the expressions within the body of the while
loop.
This makes sense. It is not the mere act of looping that is desired,
but the consequences of what happens when the expressions in the loop
are repeatedly evaluated.