Lua Variadic Arguments Basics


Example

Variadic functions are created using the ... ellipses syntax in the argument list of the function definition.

function id(...)
    return
end

If you called this function as id(1, 2, 3, 4, 5) then ... (AKA the vararg list) would contain the values 1, 2, 3, 4, 5.

Functions can take required arguments as well as ....

function head(x, ...)
    return x
end

The easiest way to pull elements from the vararg list is to simply assign variables from it.

function head3(...)
    local a, b, c = ...
    return a, b, c
end

select() can also be used to find the number of elements and extract elements from ... indirectly.

function my_print(...)
    for i = 1, select('#', ...) do
        io.write(tostring(select(i, ...)) .. '\t')
    end
    io.write '\n'
end

... can be packed into a table for ease of use, by using {...}. This places all the arguments in the sequential part of the table.

5.2

table.pack(...) can also be used to pack the vararg list into a table. The advantage of table.pack(...) is that it sets the n field of the returned table to the value of select('#', ...). This is important if your argument list may contain nils (see remarks section below).

function my_tablepack(...)
    local t = {...}
    t.n = select('#', ...)
    return t
end

The vararg list may also be returned from functions. The result is multiple returns.

function all_or_none(...)
    local t = table.pack(...)
    for i = 1, t.n do
        if not t[i] then
            return    -- return none
        end
    end
    return ...    -- return all
end