Functions
Functions group reusable behavior behind a name. A function definition uses the func keyword, followed by its name, parameters, return type, and body:
func add(a int, b int) int {
return a + b
}
Integer parameters use name int, and the return type follows the closing parenthesis.
Calls
Define a function before the first place it is called, then place arguments in parentheses:
func add(a int, b int) int {
return a + b
}
var result = add(10, 20)
print(result)
Use empty parentheses when a function does not define parameters:
exit()
The number and types of arguments must match the parameters. Because 0.2 only provides int, every user-defined parameter accepts an integer. Argument expressions are evaluated from left to right.
Optional Type Annotations
Parameter and return annotations are optional. An omitted annotation defaults to int:
func add(a, b) {
return a + b
}
This definition is equivalent to func add(a int, b int) int.
Returning Values
return requires an integer expression and immediately ends the current function:
return result
If execution reaches the end of a function without a return, Matchbox returns 0.
Some built-in functions such as print and exit are different: they do not produce a value and therefore cannot initialize a variable.
Name Resolution
Functions are resolved in source order. A call before its definition is reported as undefined. The function name is not available while its own body is parsed, so direct recursion is not supported in 0.2.
Nested function definitions are accepted, but a nested function can use its own parameters and locals or top-level names. Nested functions cannot use local variables from their enclosing function.