Macaulay2 » Documentation
Packages » Macaulay2Doc » The Macaulay2 language » control flow statements » break
next | previous | forward | backward | up | index | toc

# break -- break from a loop

- Usage:
    `break x`
- Consequences:
  - this interrupts execution of a loop controlled by for, while, apply, or scan, returning x as the value of the loop currently being evaluated.
  - Alternatively, as a top level command in the debugger, it leaves the debugger, returning the user to top level.

## Description

Omitting x, and executing break, interrupts execution of a loop as above, returning null as the value of the function currently being evaluated, except, in the case of a for loop or a while loop with a list clause, the list accumulated so far is returned as the value.

    i1 : for i from 1 to 10 do if i == 7 then break 12345

    o1 = 12345

Warning: trying to break from a loop controlled by table will probably not do what you expect, since table is implemented by two nested loops controlled by apply, and only the inner one will stop, as in the following example.

    i2 : table(3,3,(i,j) -> if i == 1 then break 3 else "hi")

    o2 = {{hi, hi, hi}, 3, {hi, hi, hi}}

    o2 : List

    i3 : table(3,3,(i,j) -> if j == 1 then break 3 else "hi")

    o3 = {3, 3, 3}

    o3 : List

Here is an example as a debugger command.

    i4 : load "Macaulay2Doc/demos/demo1.m2"

    i5 : g 2
    /usr/share/Macaulay2/Macaulay2Doc/demos/demo1.m2:8:11:(3):[2]: error: division by zero
    /usr/share/Macaulay2/Macaulay2Doc/demos/demo1.m2:8:11:(3): entering debugger (enter 'help' to see commands)
    /usr/share/Macaulay2/
    Macaulay2Doc/demos/demo1.m2:8:10-8:13: --source code:
         b := 1/x;

    ii6 : x

    oo6 = 0

    ii7 : break

    i8 : g 3

         7
    o8 = -
         2

    o8 : QQ

## See also

- apply -- apply a function to each element
- scan -- apply a function to each element in a list or sequence
- while -- while loops
- for -- for loops

## For the programmer

The object break is a keyword.

The source of this document is in /build/macaulay2-88fgJW/macaulay2-1.25.11+ds/M2/Macaulay2/packages/Macaulay2Doc/ov_language.m2:776:0.