GNU Info

Info Node: (emacs-lisp-intro.info)Incrementing Loop

(emacs-lisp-intro.info)Incrementing Loop


Next: Decrementing Loop Prev: print-elements-of-list Up: while
Enter node , (file) or (file)node

A Loop with an Incrementing Counter
-----------------------------------

   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.

Incrementing Example
Counting pebbles in a triangle.
Inc Example parts
The parts of the function definition.
Inc Example altogether
Putting the function definition together.

automatically generated by info2www version 1.2.2.9