Exit a script within a loop - Forum

Forum Navigation
You need to log in to create posts and topics.

Exit a script within a loop

Hi everyone at the forum,

if I want to exit a script within a loop, like "Loop 1 100 [counter]", what would be the correct way to do this? Can I use "ExitLoop" first and then "Return"? Or is it better to use a "While" loop instead? My thought is, ​​that a loop with defined start- and end-values, needs to be exited cleanly to avoid a stack overflow.

Thanks very much for your help :-)

Kind regards,
Joerg

@joerg use ExitLoop  to leave the current Loop ... EndLoop block. After that, execution continues after EndLoop. You only need Return as well if you want to stop the whole script/subroutine, not just the loop.

Thanks Luis! But after leaving the loop, I also want to exit the whole script. I guess, this can only be done by checking, if the loop is incomplete, right?

Kind regards,
Joerg

Hi Joerg,

you don’t need to check whether the loop completed or not.
If your goal is leave the loop and stop the whole script immediately, you can simply use Return directly from inside the loop.

Example:

Loop 1 100 [counter]
  If [counter] == 25
    Return
  EndIf
  ... other commands ...
EndLoop
... this code will never execute if Return was triggered ...

 

Return exits the current script/subroutine immediately — it does not need ExitLoop beforehand.

Use:

  • ExitLoop → leave the loop but continue executing the script after EndLoop
  • Return → leave the entire script immediately (and therefore also leave any active loop)

So this is unnecessary:

ExitLoop
Return

because Return already ends execution.

The only time you would set a flag and check afterward is if you intentionally want:

ExitLoop
...
If [abort] == "true"
   Return
EndIf

that pattern is useful when cleanup code should still run after the loop.

Kind regards,

Hi Luis,

thanks very much for your help! I didn't know, that it is possible to exit from a loop this way :-)

Kind regards,
Joerg