How to make functions receive a variable number of arguments?

Lua functions are very tolerant of extra arguments; you could take a function of no arguments and pass it arguments, and they will be simply discarded.

The syntax of functions taking an indefinite number of arguments ('variadic functions') is the same as in C:

function vararg1(arg1,...)
 local arg = {...}
 -- use arg as a table to access arguments end

What is ...? It is shorthand for all the unnamed arguments. So function I(...) return ... end is a general 'identity' function, which takes an arbitrary number of arguments and returns these as values. In this case, {...} will be filled with the values of all the extra arguments.

But, vararg1 has a not-so-subtle problem. nil is a perfectly decent value to pass, but will cause a hole in the table arg, meaning that # will return the wrong value.

A more robust solution is:

function vararg2(arg1,...)
 local arg = {n=select('#',...),...}
 -- arg.n is the real size
 for i = 1,arg.n do
 print(arg[i])
 end end

Here we use the select function to find out the actual number of arguments passed. This is such a common pattern with varargs that it has become a new function, table.pack in Lua 5.2.

You will sometimes see this in older code, which is equivalent to vararg2:

function vararg3(arg1,...)
 for i = 1,arg.n do
 print(arg[i])
 end end

However, arg used in this special way is deprecated, and it will not work with LuaJIT and Lua 5.2.



Back