Variadic Functions in Lua

Here’s a function that will take an arbitrary number of ints as arguments.

function sum(...)
    local nums = { ... }
    print(table.concat(nums, ", "))
    local total = 0

    for _, num in ipairs(nums) do
        total = total + num
    end

    print(total)
end

Within the function, the ... expression captures all arguments and packs them into a table (nums). We then iterate over this table to calculate the sum of the numbers.

Variadic functions can be called in the usual way with individual arguments.

sum(1, 2)
sum(1, 2, 3)

If you already have multiple args in a table, unpack them using table.unpack like this.

local nums = {1, 2, 3, 4}
sum(table.unpack(nums))

To run the program, save the code to a file, such as variadic-functions.lua, and use the Lua interpreter to execute it.

$ lua variadic-functions.lua
1, 2 
3
1, 2, 3 
6
1, 2, 3, 4
10

Another key aspect of functions in Lua is their ability to form closures, which we’ll look at next.