Node:Incrementing Loop, Next:Decrementing Loop, Previous:print-elements-of-list, Up:while
A loop is not useful unless it stops when it ought. Besides controlling a loop with a list, a common way of stopping a loop is to write the first argument as a test that returns false when the correct number of repetitions are complete. This means that the loop must have a counter--an expression that counts how many times the loop repeats itself.
The test can be an expression such as (< count desired-number)
which returns t
for true if the value of count
is less
than the desired-number
of repetitions and nil
for false if
the value of count
is equal to or is greater than the
desired-number
. The expression that increments the count can be
a simple setq
such as (setq count (1+ count))
, where
1+
is a built-in function in Emacs Lisp that adds 1 to its
argument. (The expression (1+ count)
has the same result as
(+ count 1)
, but is easier for a human to read.)
The template for a while
loop controlled by an incrementing
counter looks like this:
set-count-to-initial-value (while (< count desired-number) ; true-or-false-test body... (setq count (1+ count))) ; incrementer
Note that you need to set the initial value of count
; usually it
is set to 1.