Revision Difference
vararg#561751
<cat>Dev.Lua</cat>
<title>Concepts - Variadic Functions</title>⤶
<title>Concepts - Variable Argument Count (varargs)</title>⤶
# Variadic Functions
Functions that take a variable amount of arguments are called `variadic`.
<br/>
## Example
The `print` function logs any number of values you supply it to the console.
```Lua
print( 'These' , 'are' , 'a' , 'lot' , 'of' , 'arguments' , 1 , 2 , 3 )
```
<br/>
## Declaration
Variadic arguments can be declared with the name
`...` at the ends of a function's list of arguments.
```Lua
function ( first , second , ... )
```
Calling the function with `( 1 , 2 , 3 , 4 )` results in:
- `first` = `1`
- `second` = `2`
- `...` = `3 , 4`
<br/>
## Usage
You can use supply `...` as an argument to another function.
```Lua
sum( 1 , 2 , ... , 5 ) -- Same as sum( 1 , 2 , 3 , 4 , 5 )
```
<br/>
## Unpacking
You can also create variadic arguments by <page text = 'unpacking' >Global.unpack</page> a table.
```Lua
unpack({ 3 , 4 }) -- Same as `3 , 4`
```
<br/>
## Packing
The opposite can be achieved by <page text = 'packing' >table.Pack</page> a table.
```Lua
local arguments = table.Pack( ... ) -- Same as { 3 , 4 }
```
```Lua
local arguments = { ... } -- Shorthand Syntax
```
<br/>
---
<br/>
<example name = 'Summation' >
<description>
Adds up a variable numbers of values.
</description>
<code>
function sum ( ... )
local total = 0
for _ , value in ipairs({ ... }) do
total = total + value
end
return total
end
</code>
<code name = 'Test' >
print(sum(1,2,3))
</code>
<output>6</output>
</example>
<br/>
---
<br/>
<example name = 'Average' >
<description>
Finds the mean of a variable numbers of values
using the previous example's summation function.
</description>
<code name = 'Function' >
function average ( ... )
return sum( ... ) / #{ ... }
end
</code>
<code name = 'Test' >
print(average(1,2,3))
</code>
<output>2.0</output>
</example>