Loading...
The "exit" statement is a tool that can be used in every script and in combination with every other programming statement, or even without.
It enables you to abort the currently running script in the moment where it runs into the "exit" statement.
Especially useful is the combination with an if-statement, to check variables or logical expressions for a certain condition and initiate an abort if necessary.
When the script runs into an "exit", everything after this line will not be executed.
If it is used for example in a macro or function, only the execution of the script context where it occurs is stopped. Other scripts from which this script might have been called are not influenced and will continue running.
Exiting a script can be very helpful with very long and complex scripts to avoid an execution of certain parts if a specific condition is met. Note that the "exit" statement is used to stop the current script. To cancel other scripts, or other instances from the current script, use the command ScriptCancel.
Example 1:
For this example, please create first a global Boolean variable with the name "stopLoop". The expression "if stopLoop" is short for "if stopLoop = true".
stopLoop = false
for i = 0 to 1000 {
if stopLoop {
exit
}
Label1.Text = "Counting up: " + i
WDWait(1)
}
Label1.Text = "Count completed"
This script sets the variable "stopLoop" to false at the beginning and enters a for-loop, which counts up from zero to one thousand.
In every iteration, the current count value is written into Label1 and the script pauses for one second until the next iteration is started.
As long as the variable "stopLoop" remains in false state the cycle continues until Label1 would finally display "Count completed". To stop the loop before that, simply set the variable to true, e.g. with a CustomScript button and the script:
stopLoop = true
In contrary to the for-loop's "break" statement, which only exits the for-statements but resumes the script following it, the "exit" statement does not execute the last line of this example script and Label1 will show the last count.
Example 2:
Imagine a setup using several different sensor values (pressure, temperature, buttons,...) to trigger a series of events within a highly sophisticated script.
There might be a case that this series needs to be stopped if sensor number 1 and sensor number 4 show a temperature level above 42°C to prevent the setup from overheating
If this is the case, all you would need to do is add the following line at a few significant places in your script:
if (sensorValue1 > 42) AND (sensorValue4 > 42) {exit}
Whenever this state is detected, every script currently running into this condition is stopped immediately.