Menu
Coddy logo textTech

table.unpack and Varargs

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 20 of 73.

Sometimes you have values in an array but need them as separate values — say, to pass each element as its own argument. That's table.unpack: it returns all the elements of an array, spread out.

local scores: {number} = {85, 92, 78}
print(table.unpack(scores))     -- 85  92  78  (one line, three values)
print(math.max(table.unpack(scores))) -- 92 — each element became an argument

The mirror image is varargs: a function that accepts any number of arguments via .... You've seen ... in Lua — Luau lets you type it, so every incoming value must match:

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

select("#", ...) returns how many arguments arrived, and select(i, ...) returns the arguments from position i onward — used as a single value in an expression, that's effectively "the i-th argument".

The two features click together: sum(table.unpack(scores)) spreads the array straight into the vararg function — Luau's answer to the spread-call pattern you'd see in other languages. table.unpack reads the array without modifying it.

challenge icon

Challenge

Easy

Create a typed array scores: {number} with 85, 92 and 78.

  1. Print all the scores on one line using table.unpack.
  2. Print the highest score using math.max and table.unpack.
  3. Define local function sum(...: number): number that adds up all its arguments using select("#", ...) and select(i, ...), then print sum(table.unpack(scores)).
  4. Print sum(10, 20) to show the same function works with plain arguments.

Try it yourself

-- Write code here
-- 1) declare scores: {number} = {85, 92, 78}
-- 2) print(table.unpack(scores)) and the math.max of the unpacked scores
-- 3) define sum(...: number): number with select, print sum(table.unpack(scores))
-- 4) print sum(10, 20)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau