Functions
Declare named functions with func. Parameter types are written after each parameter name. A return type may be provided after the parameter list.
func add(a: int, b: int) int {
return a + b
}
func greet(name: str) {
print("Hello, {name}!")
}
print(add(2, 3))
greet("Ada")Return values
Functions without a return type return no value. Non-void functions must return a value on every path.
Multiple return values use a parenthesized type list and can be destructured at the call:
func findPort(configured: str) (str, bool) {
if configured == "" {
return "8080", false
}
return configured, true
}
val port, configured = findPort(sys.env("PORT"))Anonymous functions and closures
An anonymous function can be assigned to a variable. Closures can capture variables from the surrounding scope:
val multiply = func(a: int, b: int) int {
return a * b
}
mut count = 0
val increment = func() {
count = count + 1
}
increment()
print(multiply(3, 4))Recursion and declaration order
Named functions can call themselves and other functions declared later in the file:
func factorial(n: int) int {
if n <= 1 {
return 1
}
return n * factorial(n - 1)
}Scope
Named functions have their own local scope; local variables from the calling scope are not generally captured. ScarScript v1.0.1 allows top-level const and val initialized with literals to be referenced from functions. Anonymous functions are closures and capture their surrounding scope.
Compiler feedback
The compiler reports errors with the source location:
hello.scar:4:12: error: argument 1 expects int, got strCommon function errors include the wrong number of arguments, mismatched argument types, undefined functions, and missing returns.