Functions with Any Number of Arguments
print accepts any number of arguments: one, two, or ten. Your own functions can do the same. Write three dots, ..., as the parameter list. A function like this is called variadic.
... stands for "all the arguments that were passed". To work with them, use the built-in function select:
select("#", ...)gives the number of arguments.select(i, ...)gives the argument at positioni.
function announce(...)
local count = select("#", ...)
print("got " .. count .. " values")
for i = 1, count do
local value = select(i, ...)
io.write(value, " ")
end
print()
end
announce("red", "green", "blue")
announce(1, 2)
Output:
got 3 values
red green blue
got 2 values
1 2
The first call passes three arguments, so count is 3 and the loop runs three times. The second call passes two.
Why store select(i, ...) in a variable?
select(i, ...) actually returns the argument at position i and every argument after it. You can see this when you print the result directly:
print(select(2, "a", "b", "c"))
Output:
b c
Remember the rule from the multiple returns lesson: if you catch fewer values than were returned, the extras are dropped. So local value = select(i, ...) keeps only the one you asked for.
Fixed parameters first, then ...
A function can have normal parameters followed by .... The dots must come last. You can also pass ... straight on to another function:
function log(level, ...)
print("[" .. level .. "]", ...)
end
log("INFO", "saved", 3, "files")
Output:
[INFO] saved 3 files
level takes the first argument, and ... holds the rest. print then receives all of them.
In the exercise, complete a sum function that adds up all of its arguments.