Robert
Robert

Reputation: 2812

Retrieve the length of variable argument list

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

Answers (2)

Nicol Bolas
Nicol Bolas

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

Vinni Marcon
Vinni Marcon

Reputation: 616

function countargs(...)
  local arg = {...}
  return #arg
end

or

function countargs(...)
  return #{...}
end

Upvotes: 1

Related Questions