table construction & unpack()
Part of the Logic & Flow section of Coddy's Lua journey — lesson 6 of 54.
Lua provides a complementary pair of techniques for working with multiple values: table construction and table.unpack(). These are particularly useful when working with functions that need flexible argument handling.
You can capture multiple values into a list-style table using table constructor syntax with curly braces. This collects all the values into a single table structure.
local args = {10, 20, 30}
print(args[1]) -- Output: 10
print(#args) -- Output: 3The table.unpack() function does the opposite—it takes a list-style table and returns all its elements as separate values. This allows you to pass table contents as individual arguments to a function.
local numbers = {5, 10, 15}
print(table.unpack(numbers)) -- Output: 5 10 15These techniques work together seamlessly. You can collect values into a table, manipulate the table, and then unpack it back into individual values.
Challenge
EasyWrite a function forwardArguments that takes three numbers a, b, and c, and returns their sum by using table construction and table.unpack().
Create a table containing the three arguments using {a, b, c} syntax, then unpack them and pass them to another function that calculates their sum.
Logic:
- Use
{a, b, c}to create a table containing all three arguments - Create a separate function called
sumthat takes three parameters and returns their sum - Use
table.unpack()to pass the table values to thesumfunction - Return the result from the
sumfunction
Parameters:
a(number): First numberb(number): Second numberc(number): Third number
Returns: The sum of all three numbers (number)
Cheat sheet
Table constructor syntax {a, b, c, ...} creates a list-style table. Use # to get the element count.
local args = {10, 20, 30}
print(args[1]) -- Output: 10
print(#args) -- Output: 3table.unpack() takes a list-style table and returns all its elements as separate values, allowing you to pass table contents as individual arguments to a function.
local numbers = {5, 10, 15}
print(table.unpack(numbers)) -- Output: 5 10 15Try it yourself
function forwardArguments(a, b, c)
-- Create a separate function that calculates the sum
-- Create a table containing all three arguments
-- Unpack the table and pass values to the sum function
end
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board