Iteration means executing part of a program repetitively. For
example, you might want to repeat some computation once for each element
of a list, or once for each integer from 0 to n. You can do this
in SXEmacs Lisp with the special form while:
whilefirst evaluates condition. If the result is non-nil, it evaluates forms in textual order. Then it reevaluates condition, and if the result is non-nil, it evaluates forms again. This process repeats until condition evaluates tonil.There is no limit on the number of iterations that may occur. The loop will continue until either condition evaluates to
nilor until an error orthrowjumps out of it (see Nonlocal Exits).The value of a
whileform is alwaysnil.(setq num 0) ⇒ 0 (while (< num 4) (princ (format "Iteration %d." num)) (setq num (1+ num))) -| Iteration 0. -| Iteration 1. -| Iteration 2. -| Iteration 3. ⇒ nilIf you would like to execute something on each iteration before the end-test, put it together with the end-test in a
prognas the first argument ofwhile, as shown here:(while (progn (forward-line 1) (not (looking-at "^$"))))This moves forward one line and continues moving by lines until it reaches an empty. It is unusual in that the
whilehas no body, just the end test (which also does the real work of moving point).
Another—more powerful—way to do iteration is using the special
CL-macro loop but requires the cl-macs library to be
loaded.