Menu
CoddyTech

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))) -- 92

print 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 icon

Challenge

Easy

Spread an array of scores into separate values.

  1. Declare local scores: {number} = {64, 88, 71}.
  2. Print table.unpack(scores).
  3. 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

Practice on your own: Online Luau compiler