Variadic functions
Accept any number of trailing arguments with `...param`.
Add ...name as the **last** parameter in a function or method signature. At call time, every extra argument is collected into an **array** bound to name.
Parameters before ... are required: callers must pass at least that many arguments. A call with only the required args gives the rest parameter an empty array #[ ].
Variadic functions work for named functions, anonymous fun(...args) { } expressions, and class methods.
All arguments variadic
`...args` receives every call argument as an array, including zero.
fun sum(...args) {
var total = 0;
for (n von args) {
total = total + n;
}
return total;
}
print sum(1, 2, 3, 4, 5);
print sum(10, 20, 30);
print sum();output
15 60 0
Required params + rest
Arguments before the rest array are bound to normal parameters.
fun join(sep, ...parts) {
var result = "";
var first = true;
for (p von parts) {
if (first) {
result = p;
first = false;
} else {
result = result + sep + p;
}
}
return result;
}
print join(", ", "a", "b", "c", "d");
print join(" - ", "Rain", "is", "cool");output
a, b, c, d Rain - is - cool
Variadic method
Class methods use the same `...name` syntax as top-level functions.
class Logger {
log(prefix, ...messages) {
for (msg von messages) {
print prefix + ": " + msg;
}
}
}
var log = Logger();
log.log("INFO", "started", "ready");
log.log("DEBUG");output
INFO: started INFO: ready