Node:Decrementing Loop, Previous:Incrementing Loop, Up:while



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
  body...
  (setq counter (1- counter)))          ; decrementer