Varargs and the ... Operator
Handle variable-length argument lists using ... and select().
Variable Arguments
A Lua function can accept a variable number of arguments using ... (three dots) in the parameter list. Inside the function, ... represents the extra arguments. You can use it in expressions, pass it to other functions, or convert it to a table.
local function sum(...)
local total = 0
for _, v in ipairs({...}) do
total = total + v
end
return total
end
print(sum(1, 2, 3)) -- 6
print(sum(10, 20, 30, 40)) -- 100select() for Varargs
select(n, ...) returns arguments from position n onward. select("#", ...) returns the total count of arguments including nil values. This is safer than #{...} which stops at the first nil hole.
local function inspect(...)
local n = select("#", ...)
print("count:", n)
for i = 1, n do
print(i, select(i, ...))
end
end
inspect("a", "b", nil, "d")
-- count: 4
-- 1 a
-- 2 b
-- 3 nil
-- 4 dAll lessons in this course
- Defining and Calling Functions
- Multiple Return Values
- Varargs and the ... Operator
- Recursion in Lua