Functions¶
Defining a function¶
- Parameters are positional — Luz has no keyword or default arguments.
returnexits the function with a value.- A function that reaches the end without a
returnreturnsnull.
Multiple parameters¶
Functions as values¶
Functions are first-class values. They can be stored in variables and passed as arguments:
Nested functions¶
Functions can be defined inside other functions:
function outer() {
function inner() {
return "from inner"
}
return inner()
}
write(outer()) # from inner
Closures¶
Inner functions capture variables from their enclosing scope. The captured variable is read at call time, not at definition time:
function make_counter() {
count = 0
function increment() {
count = count + 1
return count
}
return increment
}
counter = make_counter()
write(counter()) # 1
write(counter()) # 2
write(counter()) # 3
Recursion¶
function factorial(n) {
if n <= 1 { return 1 }
return n * factorial(n - 1)
}
write(factorial(6)) # 720
Higher-order functions¶
A function that takes another function as an argument: