GNU Info

Info Node: (cl)Loop Examples

(cl)Loop Examples


Next: For Clauses Prev: Loop Basics Up: Loop Facility
Enter node , (file) or (file)node

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 `loop' language.

     (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
`loop' construct.  The result is a list of the file names of all the
buffers in Emacs' memory.  The words `for', `in', and `collect' are
reserved words in the `loop' language.

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

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

     (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.

     (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.

     (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 `for's
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 `loop' constructs if
you want nested loops.


automatically generated by info2www version 1.2.2.9