0Pricing
Lua Academy · Lesson

Iterating with ipairs

Loop over sequences in order.

Why ipairs

Walking a sequence by index works, but ipairs is cleaner and safer. It hands you each index and value in order.

It starts at index 1 and stops at the first nil, perfect for gap-free sequences.

local fruits = {"apple", "banana", "cherry"}
for i, v in ipairs(fruits) do
  print(i, v)
end

The Loop Shape

The pattern is for index, value in ipairs(t) do ... end.

On each pass, index is the 1-based position and value is the element there. No manual counter needed.

local colors = {"red", "green", "blue"}
for i, c in ipairs(colors) do
  print("Color", i, "is", c)
end

All lessons in this course

  1. Arrays as Tables
  2. Adding and Removing Items
  3. Iterating with ipairs
  4. Length and Sorting
← Back to Lua Academy