Exiting functions

There may be occasions where you want to exit out of a function dependent on certain conditions. The keyword exitfunction lets you do this. When used it immediately exits the function resulting in no further instructions beyond being executed. The following program shows it being used.

do
	myFunction ( 10, 20 )
	
sync ( ) loop
function myFunction ( a as integer, b as integer ) print ( a ) exitfunction print ( b ) endfunction

The function myFunction takes in two integer parameters (a and b). The code within the function makes a call to the print command passing in the value of a. This is followed by a call to the exitfunction command. The effect of this is such that the next call to print using the parameter b is ignored, as the function immediately exits out upon coming to exitfunction. When this program runs the only thing you will see on screen is the number 10. The call to display the value of b on screen is never executed.

This kind of functionality to exit out of a function can be useful. Let's look at the program again, but this time with a condition added in.

do
	myFunction ( 10, 20 )
	
sync ( ) loop
function myFunction ( a as integer, b as integer ) if a <= 10 exitfunction endif
print ( a ) print ( b ) endfunction

The function myFunction has an if statement that determines whether the parameter a is less than or equal to 10. If this condition is met exitfunction is used to immediately return out of the function and continue execution from where the function was called. If this condition is not met then the values of a and b are displayed on screen. Given that myFunction is called and supplied with values of 10 and 20 this function will immediately exit. If the first parameter is changed to 11 then the function will display 11 and 20 on screen.

When you need to exit out of a function that returns a value simply add the return value directly after the call to exitfunction, as shown in this example.

do
	print ( myFunction ( 10, 20 ) )
	
sync ( ) loop
function myFunction ( a as integer, b as integer ) if a <= 10 exitfunction 1 endif endfunction a + b

If the value of a within myFunction is less than or equal to 10 the function will immediately exit, returning a value of 1, otherwise the function will return the sum of a and b.