Next: , Previous: Loop Basics, Up: Loop Facility

4.7.2 Loop Examples

Before listing the full set of clauses that are allowed, let's look at a few example loops just to get a feel for the cl-loop language.

     (cl-loop for buf in (buffer-list)
              collect (buffer-file-name buf))

This loop iterates over all Emacs buffers, using the list returned by buffer-list. For each buffer buf, it calls buffer-file-name and collects the results into a list, which is then returned from the cl-loop construct. The result is a list of the file names of all the buffers in Emacs's memory. The words for, in, and collect are reserved words in the cl-loop language.

     (cl-loop repeat 20 do (insert "Yowsa\n"))

This loop inserts the phrase “Yowsa” twenty times in the current buffer.

     (cl-loop until (eobp) do (munch-line) (forward-line 1))

This loop calls munch-line on every line until the end of the buffer. If point is already at the end of the buffer, the loop exits immediately.

     (cl-loop do (munch-line) until (eobp) do (forward-line 1))

This loop is similar to the above one, except that munch-line is always called at least once.

     (cl-loop for x from 1 to 100
              for y = (* x x)
              until (>= y 729)
              finally return (list x (= y 729)))

This more complicated loop searches for a number x whose square is 729. For safety's sake it only examines x values up to 100; dropping the phrase ‘to 100’ would cause the loop to count upwards with no limit. The second for clause defines y to be the square of x within the loop; the expression after the = sign is reevaluated each time through the loop. The until clause gives a condition for terminating the loop, and the finally clause says what to do when the loop finishes. (This particular example was written less concisely than it could have been, just for the sake of illustration.)

Note that even though this loop contains three clauses (two fors and an until) that would have been enough to define loops all by themselves, it still creates a single loop rather than some sort of triple-nested loop. You must explicitly nest your cl-loop constructs if you want nested loops.