Since version 2.2
Syntax:
fun <fun_name><sigil> [(<arg1>, <arg2>, <argn> ...)] [<statements>] return <expression> endfun
The FUN … ENDFUN
directives are used for defining a user function. Functions are similar to procedures with the exception that:
The name of the function and the name of a parameter can't start with a command or directive name. For example, you can't define a function named repeatnumber
as REPEAT
is a command. Likewise, you can't name a parameter funparameter1
as FUN
is a directive.
Define your functions /before/ calling them, preferably in the beginning of your source file, like in the example bellow:
fun sum_of_integers(a, b) return a + b endfun
To define a function of a type other than integer as well as defining parameters other than integers, use sigils:
fun sum_of_bytes!(a!, b!) return a! + b! endfun
It is valid to have more than one RETURN
statements in a function:
fun max(a, b) if a > b then return a else return b endif endfun
Note there are no such things as void functions in XC=BASIC and the following will not work:
fun dont_do_this(x) rem -- no return statement endfun
If you want a routine that does not return a value, use Procedures instead.
You can omit the parameter list, but bear in mind that you still have to write the empty parentheses:
fun no_params() ... endfun
You can call a function from within an expression by using the function name, sigil and the argument list in parentheses, for example:
let x! = my_function!(a, b!) * 2
Note that in the example above my_function!
is a function that returns a byte and accepts an integer and a byte as arguments.
Important note: you must pass exactly the same amount of parameters and the parameter types must match those in the function definition.
While procedures do support direct recursion, functions don't.