www.delorie.com/gnu/docs/emacs-lisp-intro/emacs-lisp-intro_159.html   search  
Buy the book!

Programming in Emacs Lisp

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.1.3 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:

(while (< count desired-number)         ; true-or-false-test
  (setq count (1+ count)))              ; incrementer

Note that you need to set the initial value of count; usually it is set to 1.

Example with incrementing counter  Counting pebbles in a triangle.
The parts of the function definition  
Putting the function definition together  

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003