Loop Basics
-----------
The `loop' macro essentially creates a mini-language within Lisp that
is specially tailored for describing loops. While this language is a
little strange-looking by the standards of regular Lisp, it turns out
to be very easy to learn and well-suited to its purpose.
Since `loop' is a macro, all parsing of the loop language takes
place at byte-compile time; compiled `loop's are just as efficient as
the equivalent `while' loops written longhand.
- Special Form: loop clauses...
A loop construct consists of a series of CLAUSEs, each introduced
by a symbol like `for' or `do'. Clauses are simply strung
together in the argument list of `loop', with minimal extra
parentheses. The various types of clauses specify
initializations, such as the binding of temporary variables,
actions to be taken in the loop, stepping actions, and final
cleanup.
Common Lisp specifies a certain general order of clauses in a loop:
(loop NAME-CLAUSE
VAR-CLAUSES...
ACTION-CLAUSES...)
The NAME-CLAUSE optionally gives a name to the implicit block that
surrounds the loop. By default, the implicit block is named
`nil'. The VAR-CLAUSES specify what variables should be bound
during the loop, and how they should be modified or iterated
throughout the course of the loop. The ACTION-CLAUSES are things
to be done during the loop, such as computing, collecting, and
returning values.
The Emacs version of the `loop' macro is less restrictive about
the order of clauses, but things will behave most predictably if
you put the variable-binding clauses `with', `for', and `repeat'
before the action clauses. As in Common Lisp, `initially' and
`finally' clauses can go anywhere.
Loops generally return `nil' by default, but you can cause them to
return a value by using an accumulation clause like `collect', an
end-test clause like `always', or an explicit `return' clause to
jump out of the implicit block. (Because the loop body is
enclosed in an implicit block, you can also use regular Lisp
`return' or `return-from' to break out of the loop.)
The following sections give some examples of the Loop Macro in
action, and describe the particular loop clauses in great detail.
Consult the second edition of Steele's "Common Lisp, the Language", for
additional discussion and examples of the `loop' macro.