29 of 172
ZBasic Language Reference 22 ZX Microcontroller Family The last statement of the function, just before the End Function, illustrates how the value to be returned by the function is set. It is useful to think of there being a variable automatically defined that has the same name as the function as well as the same type. We call this a return value variable. Within the function, you can refer to the return value variable, in most cases, just as you would any other variable or parameter. In the example above, instead of introducing a new variable factVal, we could have instead simply used the reference to the return value variable Factorial. The function’s code is re-written below using this idea. Function Factorial(ByVal val as Long) As Long Factorial = 1 Do While (val > 1) Factorial = Factorial * val val = val - 1 Loop End Function As with subroutines, variables and constants may be defined within a function. When this is done, the variable or constant is private to the function and cannot be directly accessed from any other routine. Although it is common to place such definitions near the beginning of the function, the definitions may occur anywhere in the subroutine as long as they occur before their first use. Note that the normal execution sequence of a function may be altered by using the Exit Function statement. When executed, this statement causes control to return to the caller immediately. Also, it is important to know that the return value variable of a function is not automatically initialized. If your function returns without having assigned a value to the return value variable, the return value will have an undefined value. Once a function is defined, it may be used anywhere a variable may be used, e.g. in an expression. One exception is that a function name may not be used on the left hand side of an assignment. Dim lval as Long lval = Factorial(4) If a function is defined as taking zero parameters, it may be invoked by giving its name without the parentheses following it. This form is supported for compatibility reasons but its use is discouraged. If the parentheses are present a reader of the code knows immediately that it is a function invocation as opposed to the use of a variable or constant. BasicX Compatibility Note In BasicX compatibility mode, when a function is defined as returning an UnsignedInteger or UnsignedLong type, the very first line of the function must be a Set statement 2.4 Expressions Expressions are an important part of most ZBasic programs. They provide the means by which your programs implement the mathematical, logical and comparison operations necessary for your application. Generally, anywhere a value may be used, an expression may be used as well. An expression consists of one or more values, called operands, and one or more operators that indicate the function to perform on the operands. Example b = b * 5 + 3