Iterating with ipairs()
Part of the Logic & Flow section of Coddy's Lua journey — lesson 2 of 54.
While pairs() works with any table structure, Lua provides a specialized function called ipairs() specifically designed for list-style tables. This function iterates through tables in sequential order, starting from index 1 and continuing until it encounters a nil value.
The syntax for ipairs() is similar to pairs():
for index, value in ipairs(myList) do
-- use index and value here
endHere's an example with a list of quest items:
local questItems = {"Map", "Compass", "Torch", "Rope"}
for i, item in ipairs(questItems) do
print(i .. ". " .. item)
endOutput:
1. Map
2. Compass
3. Torch
4. RopeThe key difference from pairs() is that ipairs() stops immediately when it finds a nil value, even if there are more elements after it.
Challenge
EasyWrite a function listTasks that takes a tasks table and returns a formatted string listing all tasks with their position numbers.
Use ipairs() to iterate through the tasks in sequential order and build a string where each line shows the task number followed by the task name in the format number. task. Each task should be on a separate line.
Parameters:
tasks(table): A list-style table containing task names as strings
Returns: A string with each task numbered on a separate line. Format:
1. task1
2. task2
3. task3Cheat sheet
ipairs() iterates through list-style tables in sequential order, starting from index 1 and stopping at the first nil value:
for index, value in ipairs(myList) do
-- use index and value here
endExample:
local questItems = {"Map", "Compass", "Torch", "Rope"}
for i, item in ipairs(questItems) do
print(i .. ". " .. item)
end
-- Output:
-- 1. Map
-- 2. Compass
-- 3. Torch
-- 4. RopeKey difference: Unlike pairs(), ipairs() stops immediately when it encounters a nil value, even if more elements exist after it.
Try it yourself
function listTasks(tasks)
-- 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