Defined functions are similar to defined subroutines with the main difference being that the function is used to return a value in an expression.
For example, if you wanted a function to select the maximum of two values you could define:
1 2 3 4 5 6 7 |
Function Max(a, b) If a > b Max = a Else Max = b EndIf End Function |
Then you could use it in an expression:
1 2 |
SetPin 1, 1 : SetPin 2, 1 Print "The highest voltage is" Max(Pin(1), Pin(2)) |
The rules for the argument list in a function are similar to subroutines. The only difference is that brackets are required around the argument list when you are calling a function (they are optional when calling a subroutine).
To return a value from the function you assign a value to the function’s name within the function. If the function’s name is terminated with a $ the function will return a string, otherwise it will return a number.
Within the function the function’s name acts like a standard variable.
As another example, let us say that you need a function to format time in the AM/PM format:
1 2 3 4 5 6 7 8 9 10 11 |
Function MyTime$(hours, minutes) Local h h = hours If hours > 12 Then h = h - 12 MyTime$ = Str$(h) + ":" + Str$(minutes) If hours <= 12 Then MyTime$ = MyTime$ + "AM" Else MyTime$ = MyTime$ + "PM" EndIf End Function |
As you can see, the function name is used as an ordinary local variable inside the subroutine. It is only when the function returns that the value assigned to MyTime$ is made available to the expression that called it. This example also illustrates that you can use local variables within functions just like subroutines.
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 the Swap subroutine (discussed above):
1 |
Swap dat(i), dat(I + 1) |
This type of construct is often used in sorting arrays.
Leave a Reply