Iterating with pairs()
Part of the Logic & Flow section of Coddy's Lua journey — lesson 1 of 54.
pairs() function makes this possible by allowing you to loop through all entries in a table, regardless of what type the keys are.The syntax for using pairs() in a for loop looks like this:for key, value in pairs(myTable) do
-- use key and value here
endpairs() provides both the key and its corresponding value. This means you can access and work with both pieces of information at the same time.Here's a practical example with a player's inventory:local inventory = {
sword = 1,
potion = 5,
gold = 150
}
for item, quantity in pairs(inventory) do
print(item .. ": " .. quantity)
endpairs() function works with any key type, including strings, numbers, or even other tables.Working with StringsIn Lua, you can join strings together using the concatenation operator, which is two dots (..). For example, "Hello" .. " " .. "World" results in "Hello World".If you need to format text across multiple lines, you can use the newline escape character, "\n". When Lua encounters "\n" inside a string, it treats it as a command to move to the next line.For example, print("Line 1\nLine 2") will output:Line 1
Line 2Challenge
EasyWrite a function printInventory that takes an inventory table and returns a formatted string listing all items and their quantities.
Use pairs() to iterate through the inventory table and build a string where each line shows an item name followed by its quantity in the format item: quantity. Each item should be on a separate line.
To place each item on its own line, use the newline character "\n" between entries. For example, "apple: 5\nbanana: 3" will display as two separate lines. Be careful not to add a leading "\n" before the first item — only add it between items.
Parameters:
inventory(table): A dictionary-style table where keys are item names (strings) and values are quantities (numbers)
Returns: A string with each item and quantity on a separate line, separated by "\n". Example output for {apple=5, banana=3}:apple: 5banana: 3
Try it yourself
function printInventory(inventory)
-- To format the output, you can concatenate strings using the '..' operator.
-- To add a new line, use the special character '\n'.
-- You might need a way to track if you are adding the first item or a subsequent one
-- to decide whether to add a newline before the item.
-- Write code here
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