Previous: , Up: while   [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
  body…
  (setq counter (1- counter)))          ; decrementer
This page has generated for branch:work/add_lispintr, commit:65845cf60c073f2f3182d1d07483530e9bbe1d96 to check Japanese translation.