Skip to main content

block

block Special Operator

Syntax:

block name form* → {result}*

Data and Control

Arguments and Values:

name—a symbol.

form—a form.

results—the values of the forms if a normal return occurs, or else, if an explicit return occurs, the values that were transferred.

Description:

block establishes a block named name and then evaluates forms as an implicit progn.

The special operators block and return-from work together to provide a structured, lexical, non-local exit facility. At any point lexically contained within forms, return-from can be used with the given name to return control and values from the block form, except when an intervening block with the same name has been established, in which case the outer block is shadowed by the inner one.

The block named name has lexical scope and dynamic extent.

Once established, a block may only be exited once, whether by normal return or explicit return.

Examples:

(block empty) → NIL 
(block whocares (values 1 2) (values 3 4)) → 3, 4
(let ((x 1))
(block stop (setq x 2) (return-from stop) (setq x 3))
x)2
(block early (return-from early (values 1 2)) (values 3 4)) → 1, 2
(block outer (block inner (return-from outer 1)) 2)1
(block twin (block twin (return-from twin 1)) 2)2
;; Contrast behavior of this example with corresponding example of CATCH.
(block b
(flet ((b1 () (return-from b 1)))
(block b (b1) (print ’unreachable))
2))1

See Also:

return, return-from, Section 3.1 (Evaluation)

Notes:

catch

Expanded Reference: block

An empty block returns NIL

A block with no body forms returns NIL.

(block done)
=> NIL

Normal return from a block

When no return-from is used, the block returns the values of its last form, like an implicit progn.

(block compute
(+ 1 2)
(+ 3 4)
(+ 5 6))
=> 11

Early exit with return-from

return-from transfers control out of the named block immediately and returns the specified value.

(block search
(dolist (x '(1 2 3 4 5))
(when (= x 3)
(return-from search x)))
nil)
=> 3

Blocks established by defun

Every function defined with defun has an implicit block named after the function. You can use return-from with the function name to exit early.

(defun find-even (list)
(dolist (x list)
(when (evenp x)
(return-from find-even x)))
nil)

(find-even '(1 3 5 4 7))
=> 4
(find-even '(1 3 5 7))
=> NIL

Blocks have lexical scope

A return-from must be lexically contained within the block it refers to. Inner blocks with the same name shadow outer ones. Here, the return-from targets the inner block named twin, so the outer block continues to evaluate and returns 2.

(block twin
(block twin
(return-from twin 1))
2)
=> 2

Returning multiple values from a block

return-from can pass multiple values out of a block.

(block multi
(return-from multi (values 10 20 30))
(print "not reached"))
=> 10
=> 20
=> 30