Jul 03 2018, 11:25 AM PST 5 min

A variadic function is a function that will accept any number of arguments, unlike a regular function which takes a predefined number.

### Library functions

The Lua and Roblox libraries contain a number of variadic functions. You may not have realized it, but `print()` is a variadic function.

Code

``````print(2, "+", 2, "=", 2+2)
print( string.format("The %s is a %s!", "cake", "lie") )
print( string.byte(115, 101, 99, 114, 101, 116) )
``````

Output

``````2 + 2 = 4
The cake is a lie!
secret
``````

### Usage

To define a variadic function, you use the “…” token as the last (or only) parameter. (not to be confused with “…”, the concatenation operator). The three dots can be used in the function later as through they were a set of variables. Most often, though, it it most convenient to pack the arguments into a table:

Code

``````local function variadic(named, ...)
local arguments = {...} -- pack the extra arguments into a table
print("Named argument = ", named)
for i, value in ipairs(arguments) do
print("Input No. ", i, "=", value)
end
end

``````

Output

``````Named argument = 10
Input No. 1 = Hi
Input No. 2 = 20
Input No. 3 = Variadic Function
``````

We could also use this to write a “sum” function:

Code

``````function sum(...)
local sum = 0
for _, value in ipairs({...}) do
sum = sum + value
end
return sum
end
print( sum(1, 2, 3, 4) )
print( sum(9, 8, 7, 6, 5, 4, 3) )
``````

Output

``````10
42
``````

#### Argument forwarding

Another common use of this feature is argument forwarding. For example, we might want to print before and after calling a function:

``````local function printAround(func)
print("Before")
func()
print("After")
end

local function foo()
print("bar")
end

printAround(foo)
``````

Output

``````Before
bar
After
``````

But what if we want to give `foo()` arguments? We can use the `...` token to do this:

Code

``````local function printAround(func, ...)
print("Before")
func(...)
print("After")
end

local function foo(x, y, z)
print("x =", x)
print("y + z =", y + z)
end

printAround(foo, 1, 2, 3)
``````

Output

``````Before
x = 1
y + z = 5
After
``````

#### Calling a variadic function from a table of arguments

Sometimes, you’ll have a table of values that you want to pass to a variadic function. To do this, you use the `unpack()` function.

Code

``````local squares = {1, 4, 9, 16, 25}
print( "The first 5 square numbers are:", unpack(squares) )
``````

Output

``````The first 5 square numbers are 1 4 9 16 25
Note that if you write a function taking variadic arguments, and find yourself unpacking tables of values, you should probably instead just pass the table directly to the function.
``````
Tags:
• coding
• concept
• lua