table construction & unpack()
Part of the Logic & Flow section of Coddy's Lua journey — lesson 6 of 54.
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: 3unpack() 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.Important: While newer versions of Lua (5.2+) moved this function to table.unpack(), this environment runs Lua 5.1, so you must use the global unpack() function.local numbers = {5, 10, 15}
print(unpack(numbers)) -- Output: 5 10 15Challenge
EasyWrite a function forwardArguments that takes three numbers a, b, and c, and returns their sum by using table construction and 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.
Note: Please use the global unpack() function rather than table.unpack() to ensure compatibility with this environment.
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
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)
Try 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
-- Hint: Use the global 'unpack' function to expand the table arguments
endThis 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