Variable arguments
Three dots let a function accept any number of arguments.
In this page:
Variable arguments
A function declared with ... in its parameter list is variadic. Inside it, ... is an expression list, and select("#", ...) gives the count while select(n, ...) returns arguments from position n onward. table.pack(...) or {...} collects them into a table. The count from select is correct even when some arguments are nil.
Note:
Use table.pack(...) instead of {...} when arguments can be nil, because it records n.
Example: Variable arguments
local function sum(...)
local total = 0
for _, v in ipairs({...}) do total = total + v end
return total
end
print(sum(1, 2, 3, 4))
local function count(...)
return select("#", ...)
end
print(count(), count(nil, nil), count(1, 2, 3))
print(select(2, "a", "b", "c"))
print(select(-1, "a", "b", "c"))
-- Output:
-- 10
-- 0 2 3
-- b c
-- c
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using {...} and trusting # when nil values are passed
- Trying to index ... directly
- Forgetting that ... is only valid inside a vararg function
Chapter Summary
- ... makes a function variadic
- select("#", ...) counts arguments
- select(n, ...) skips to n
- table.pack keeps nils safe with n
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: