Defined subroutines and functions are useful features to help in organizing programs so that they are easy to modify and read. A defined subroutine or function is simply a block of programming code that is contained within a module and can be called from anywhere within your program. It is the same as if you have added your own command or function to the language.
For example, assume that you would like to have the command FLASH added to MMBasic, its job would be to flash the power light on the Maximite.
You could define a subroutine like this:
1 2 3 4 5 |
Sub FLASH Pin(0) = 1 Pause 100 Pin(0) = 0 End Sub |
Then, in your program you just use the command FLASH to flash the power LED.
For example:
IF A <= B THEN FLASH
If the FLASH subroutine was in program memory you could even try it out at the command prompt, just like any command in MMBasic. The definition of the FLASH subroutine can be anywhere in the program but typically it is at the start or end. If MMBasic runs into the definition while running your program it will simply skip over it.
END SUB
There can be only one END SUB or END FUNCTION for each definition of a subroutine or function. To exit early from a subroutine (ie, before the END SUB command has been reached) you can use the EXIT SUB command. This has the same effect as if the program reached the END SUB statement. Similarly you can use EXIT FUNCTION to exit early from a function.
Arrays
You cannot use arrays in a subroutine or function’s argument list however the caller can use them.
For example, this is a valid way of calling a Swap subroutine:
Swap dat(i), dat(I + 1)
This type of construct is often used in sorting arrays.
Leave a Reply