1. exit

Terminates the innermost enclosing loop.

1.1. Syntax

– exit → –

1.2. Stack Effects

Table 1. Before/After
Level Object

(none)

Exits innermost loop context

1.3. Description

exit terminates execution of the innermost, dynamically enclosing looping context, regardless of lexical relationship.

Valid looping contexts created by:

exit pops the execution stack to the level of the loop operator, then resumes execution at the next object after that operator.

1.4. PostScript Level

Level 1 and later

1.5. Examples

Exit from for loop
0 1 10 {
  dup 5 eq { exit } if
  =
} for
% Prints: 0 1 2 3 4 (stops at 5)
Exit from repeat
10 {
  randomCondition { exit } if
  doWork
} repeat
Exit from loop
{
  getData
  dup endMarker eq { pop exit } if
  process
} loop
Exit from forall
[1 2 3 4 5] {
  dup 3 eq { exit } if
  10 mul
} forall
% Stack: 10 20 (stopped at 3)

1.6. Common Use Cases

1.6.1. Search with Early Exit

/findInArray {  % array value => index or -1
  false 0
  3 -1 roll {
    3 index eq {
      exch pop true exch exit
    } if
    1 add
  } forall
  exch { } { pop -1 } ifelse
} def

1.6.2. Conditional Loop Termination

{
  processItem
  shouldStop { exit } if
} loop

1.6.3. Breaking from Nested Loops

/found false def
1 1 10 {
  /i exch def
  1 1 10 {
    /j exch def
    i j testCondition {
      /found true def
      exit  % Exits inner loop only
    } if
  } for
  found { exit } if  % Exit outer loop
} for

1.7. Common Pitfalls

Must Be in Loop - exit only works within a looping context.
{ exit } if  % Error: invalidexit (not in loop)
Exits Innermost Loop Only - In nested loops, only exits the immediately enclosing loop.
1 1 10 {
  1 1 10 {
    exit  % Only exits inner loop
  } for
} for
Cannot Exit run or stopped - Attempting to exit these contexts causes [invalidexit].
{ { exit } loop } stopped  % Error: invalidexit
Use Flag for Outer Loop Exit - Set a flag variable to exit multiple levels.

1.8. Error Conditions

Error Condition

[invalidexit]

No enclosing loop context, or attempted to exit run/stopped

1.9. Implementation Notes

  • Unwinds execution stack to loop level

  • Very fast operation

  • Does not affect operand or dictionary stacks

  • Only affects execution flow

1.10. See Also

  • for - Numeric loop

  • repeat - Fixed repetition

  • loop - Indefinite loop

  • stop - Exit stopped context

  • forall - Collection iteration


Back to top

Copyright © 2025 Ribose. PostScript is a trademark of Adobe. Distributed under the MIT License.