luaguides

select

select extracts elements from a variadic argument list. It returns either all arguments after a given position, or the total count of arguments when used with '#'.

Signature

select(index, ...)

Parameters:

  • index — a number (position), or the string "#" (count mode)
  • ... — variadic arguments

Returns: If index is a number, returns all arguments from that position onward. If index is "#", returns the count of arguments.

Counting Arguments

select("#", ...) returns the number of variadic arguments:

select("#", 1, 2, 3)              -- 3
select("#", "a", "b", "c")        -- 3
select("#")                         -- 0

This is the standard way to get the count of variadic arguments in Lua, since the ... expression itself does not expose a length.

Getting Elements by Position

When index is a number, select returns all arguments from that position onward:

select(1, "a", "b", "c")          -- "a", "b", "c"
select(2, "a", "b", "c")          -- "b", "c"
select(3, "a", "b", "c")           -- "c"

Negative Index

Negative indices count from the end:

select(-1, "a", "b", "c")         -- "c"
select(-2, "a", "b", "c")          -- "b", "c"
select(-3, "a", "b", "c")          -- "a", "b", "c"

A negative index of -n returns all elements starting from n positions from the end.

Practical Examples

Iterating Over Variadic Arguments

function sum(...)
    local total = 0
    for i = 1, select("#", ...) do
        total = total + select(i, ...)
    end
    return total
end

sum(1, 2, 3, 4)    -- 10

Safely Accessing the Last Argument

function last(...)
    return select(-1, ...)
end

last(10, 20, 30)    -- 30

Ignoring the First Argument

function rest(...)
    return select(2, ...)
end

rest("first", "second", "third")    -- "second", "third"

Processing Pairs of Arguments

function pairs_sum(...)
    local total = 0
    local n = select("#", ...) / 2
    for i = 1, n do
        local key, val = select(2 * i - 1, ...)
        total = total + val
    end
    return total
end

pairs_sum("a", 1, "b", 2, "c", 3)    -- 6

Relationship to the arg Table

In Lua 5.0 through 5.1, variadic arguments were accessed through the arg pseudo-table. select was introduced in Lua 5.2 as part of the vararg expression redesign. In modern Lua (5.2+), select replaces the old arg approach:

-- Old Lua 5.1 style:
function old_sum(...)
    local n = arg.n
    local total = 0
    for i = 1, n do
        total = total + arg[i]
    end
    return total
end

-- Modern Lua 5.3+ style:
function new_sum(...)
    local total = 0
    for i = 1, select("#", ...) do
        total = total + select(i, ...)
    end
    return total
end

See Also