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 argumentThe 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
endselect("#", ...) 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
EasyCreate a typed array scores: {number} with 85, 92 and 78.
- Print all the scores on one line using
table.unpack. - Print the highest score using
math.maxandtable.unpack. - Define
local function sum(...: number): numberthat adds up all its arguments usingselect("#", ...)andselect(i, ...), then printsum(table.unpack(scores)). - 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps