Menu
Coddy logo textTech

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
end

Here'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)
end

Output:

1. Map
2. Compass
3. Torch
4. Rope

The key difference from pairs() is that ipairs() stops immediately when it finds a nil value, even if there are more elements after it.

challenge icon

Challenge

Easy

Write 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. task3

Cheat 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
end

Example:

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. Rope

Key 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow