pairs() vs. ipairs()
Part of the Logic & Flow section of Coddy's Lua journey — lesson 3 of 54.
Now that you've learned both pairs() and ipairs(), it's important to understand when to use each one. The choice depends entirely on the structure of your table and what you're trying to accomplish.
Use ipairs() when you have a list-style table with sequential integer keys starting from 1. It processes elements in order and stops at the first nil value, making it perfect for arrays where order matters.
Use pairs() when your table has string keys, mixed key types, or when you need to access all entries regardless of gaps. It iterates through every key-value pair in the table without any specific order.
Consider this mixed table:
local gameData = {
"Level 1",
"Level 2",
"Level 3",
currentLevel = 2,
playerName = "Hero"
}If you use ipairs(), you'll only see the three level strings. If you use pairs(), you'll see all five entries including the string keys.
Challenge
EasyWrite a function countSequentialItems that takes a data table and returns the count of sequential integer-keyed items.
Use ipairs() to count how many items exist in the sequential portion of the table (starting from index 1 until the first nil). This will help you understand the difference between ipairs() and pairs() when working with mixed tables.
Parameters:
data(table): A mixed table containing both sequential integer keys and string keys
Returns: The number of sequential items (number)
Cheat sheet
Use ipairs() for list-style tables with sequential integer keys starting from 1. It processes elements in order and stops at the first nil value:
for i, value in ipairs(myList) do
-- processes sequential items only
endUse pairs() for tables with string keys, mixed key types, or when you need to access all entries regardless of gaps. It iterates through every key-value pair without specific order:
for key, value in pairs(myTable) do
-- processes all key-value pairs
endExample with a mixed table:
local gameData = {
"Level 1",
"Level 2",
"Level 3",
currentLevel = 2,
playerName = "Hero"
}
-- ipairs() only sees: "Level 1", "Level 2", "Level 3"
-- pairs() sees all five entriesTry it yourself
function countSequentialItems(data)
-- Write code here
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