4.7.1 Loop Basics

The cl-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 cl-loop is a macro, all parsing of the loop language takes place at byte-compile time; compiled cl-loops are just as efficient as the equivalent while loops written longhand.

Macro: cl-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 cl-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-clausesaction-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 cl-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 cl-return or cl-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 for additional discussion and examples.