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)
endThe 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)
endAll lessons in this course
- Arrays as Tables
- Adding and Removing Items
- Iterating with ipairs
- Length and Sorting