REBOL 3 Docs Guide Concepts Functions Datatypes Errors
  TOC < Back Next >   Updated: 17-Aug-2010 Edit History  

REBOL 3 Functions: break

break  /return  value

Breaks out of a loop, while, until, repeat, foreach, etc.

Refinements:

/return - Forces the loop function to return a value

value [any-type!]

See also:

continue   catch   exit   return   loop   repeat   for   forall   foreach   forever   forskip   while   until  

Description

The break function stops loop functions.

For example:

repeat n 5 [
    print n
    if n > 2 [break]
]
1
2
3

The current loop is immediately terminated and evaluation resumes after the repeat function.

Return Value

The break /return refinement will return a value from a loop. It is commonly used to return a specific value or pass to a conditional expression when the loop is terminated early.

Here's an example:

print repeat n 5 [
    if n > pi [break/return n]
    none
]
4

An example using foreach :

values: [8:30 breakfast 12:00 lunch 5:00 dinner]
meal: foreach [time event] [
    if time > 14:00 [break/return event]
    none
]
probe meal
dinner

Important Scoping Rule

The break function acts immediately on the "closest block".

Although break can be placed anywhere within the block being repeated, even within a sub-block or function, because break is a function that is not directly bound to the loop, it will break the closest loop, not necessarily the intended loop. This does not affect most programs but could affect custom-made loop functions.

In this example, even though the break appears in the repeat loop, it applies to the a-loop loop block and has no effect on the outer repeat loop.

a-loop: func [count block] [loop count block]
repeat a 3 [
    print a
    a-loop 4 [break]
]
1
2
3


  TOC < Back Next > REBOL.com - WIP Wiki Feedback Admin