Reputation: 2812
function countargs(...)
return #arg
end
> countargs(1, 2, 3)
0
In this case, countargs returns 0 and not 3. How to retrieve the length of the variable argument list?
I tested against Lua 5.3 and 5.4 on Windows.
Upvotes: 1
Views: 819
Reputation: 473272
The number of elements in ...
can be computed via select("#", ...)
. Note that this will include any embedded nil
elements, unlike syntaxes like #{...}
.
However, you generally don't need the length directly; what you really need is a table containing the elements in question. To build this, call table.pack(...)
. This will return a table containing all of the ...
elements, and the length will be at the key "n"
, which allows you to iterate over even the embedded nil
elements of ...
.
Upvotes: 1
Reputation: 616
function countargs(...)
local arg = {...}
return #arg
end
or
function countargs(...)
return #{...}
end
Upvotes: 1