table.unpack
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 21 of 80.
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)
print(math.max(table.unpack(scores))) -- 92print receives three arguments, so it prints them on one line with a tab between them. math.max wants separate numbers, not an array, so unpacking is what makes the call work.
table.unpack reads the array without changing it. The other direction, a function that takes any number of arguments with ..., comes in the Variadic Functions lesson of the next chapter.
Challenge
EasySpread an array of scores into separate values.
- Declare
local scores: {number} = {64, 88, 71}. - Print
table.unpack(scores). - Print
math.max(table.unpack(scores)).
Press Run Code: the output shows 64 88 71 on one line, then 88.
Try it yourself
-- 1) declare scores: {number} = {64, 88, 71}
-- 2) print the unpacked scores, then their math.max
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 ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe '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 TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler