In Lua, to pass variable number of arguments, we can use ...
(three ellipses) syntax in function argument.
Lua tutorial here tells us to use arg
variable to access variadic arguments passed to functions.
According to discussions here, this only works for Lua 5.0 and has been removed in Lua 5.1.
See also changelog here:
- The vararg system changed from the pseudo-argument
arg
with a table with the extra arguments to the vararg expression. (See compile-time optionLUA_COMPAT_VARARG
inluaconf.h
.)
Instead, we can emulate that using the following code:
local arg = {...}
To get the number of extra arguments, we can use select('#', ...)
:
function my_fun(a, b, ...)
local n = select('#', ...)
print('num of extra arg:', n)
end
Note that when first argument to select is a number,
select()
will return all variable arguments starting from that index.
local v1, v2, v3, v4 = select(1, 'ab', 'b', 'c') -- v1: 'ab', v2: 'b', v3: 'c', v4: nil
local v1, v2, v3, v4 = select(2, 'ab', 'b', 'c') -- v1: 'b', v2: 'c', v3: nil, v4: nil
local v1, v2, v3, v4 = select(3, 'ab', 'b', 'c') -- v1: 'c', v2: nil, v3: nil, v4: nil
local v1, v2, v3, v4 = select(4, 'ab', 'b', 'c') -- all these variable is nil
As another example, we can calculate the sum of all arguments:
local fun = function (a, b, ...)
local sum = 0
sum = sum + a
sum = sum + b
local vararg = {...}
for _, v in pairs(vararg) do
sum = sum + v
end
return sum
end
print(fun(1, 2, 3, 4))