Revision Difference
vararg#519712
<cat>Dev.Lua</cat>⤶
Varargs are variable number of arguments, meaning the amount of arguments is undefined.
The most notable function to take varargs is <page>Global.print</page>.
To create a function with varargs, you must set the **last** parameter of the function to **...** (that's three periods). You may use a combination of normal arguments with varargs, but the varargs **must** appear as the last parameter. Inside of the function's body, you may access each argument by creating a table of the varargs with **{ ... }**
In the table, each key is the respective number of the argument, with the value being the value passed.
Varargs are stored at negative indices, so functions such as <page>debug.getlocal</page> may access the values where -1 is the first vararg passed, -2 is the second, etc.
You may create varargs yourself with <page>Global.unpack</page>.
<example>
<description>Finds the average of a set of numbers.</description>
<code>
function average(...)
local args = {...}
local result = 0
for k, v in pairs(args) do
result = result + v
end
return result / #args
end
print(average(5, 15, 30, 7, 52))
</code>
<output>21.8</output>
</example>