Next: Iteration, Previous: Conditionals, Up: Control Structure
Common Lisp blocks provide a non-local exit mechanism very
similar to catch and throw, with lexical scoping.
This package actually implements cl-block
in terms of catch; however, the lexical scoping allows the
byte-compiler to omit the costly catch step if the
body of the block does not actually cl-return-from the block.
The forms are evaluated as if by a
progn. However, if any of the forms execute(cl-return-fromname), they will jump out and return directly from thecl-blockform. Thecl-blockreturns the result of the last form unless acl-return-fromoccurs.The
cl-block/cl-return-frommechanism is quite similar to thecatch/throwmechanism. The main differences are that block names are unevaluated symbols, rather than forms (such as quoted symbols) that evaluate to a tag at run-time; and also that blocks are always lexically scoped. In a dynamically scopedcatch, functions called from thecatchbody can alsothrowto thecatch. This is not an option forcl-block, where thecl-return-fromreferring to a block name must appear physically within the forms that make up the body of the block. They may not appear within other called functions, although they may appear within macro expansions orlambdas in the body. Block names andcatchnames form independent name-spaces.In true Common Lisp,
defunanddefmacrosurround the function or expander bodies with implicit blocks with the same name as the function or macro. This does not occur in Emacs Lisp, but this package providescl-defunandcl-defmacroforms, which do create the implicit block.The Common Lisp looping constructs defined by this package, such as
cl-loopandcl-dolist, also create implicit blocks just as in Common Lisp.Because they are implemented in terms of Emacs Lisp's
catchandthrow, blocks have the same overhead as actualcatchconstructs (roughly two function calls). However, the byte compiler will optimize away thecatchif the block does not in fact contain anycl-returnorcl-return-fromcalls that jump to it. This means thatcl-doloops andcl-defunfunctions that don't usecl-returndon't pay the overhead to support it.