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

Programming in Emacs Lisp

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

11.1.4 Loop with a Decrementing Counter

Another common way to write a while loop is to write the test so that it determines whether a counter is greater than zero. So long as the counter is greater than zero, the loop is repeated. But when the counter is equal to or less than zero, the loop is stopped. For this to work, the counter has to start out greater than zero and then be made smaller and smaller by a form that is evaluated repeatedly.

The test will be an expression such as (> counter 0) which returns t for true if the value of counter is greater than zero, and nil for false if the value of counter is equal to or less than zero. The expression that makes the number smaller and smaller can be a simple setq such as (setq counter (1- counter)), where 1- is a built-in function in Emacs Lisp that subtracts 1 from its argument.

The template for a decrementing while loop looks like this:

(while (> counter 0)                    ; true-or-false-test
  (setq counter (1- counter)))          ; decrementer

Example with decrementing counter  More pebbles on the beach.
The parts of the function definition   
Putting the function definition together   

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