Lesson 16 of 55
9 mins readPython Generic for & ipairs() Array Iteration
In Plain English
`ipairs(table)` is an iterator function tailored for sequences (integer keys `1, 2, ... N`). It yields `(index, value)` pairs and stops at the first `nil` element.
Deep Dive: How It Works
1-Based Indexing: Lua array sequences start at index 1.
ipairs Behavior: Iterates `t[1], t[2], ...` consecutively until `t[i]` is nil.
Fast Sequential Scanning: Preferred iterator when table is used as an ordered list.
Core Rules to Remember

ipairs() for Arrays: Iterates numeric index-value pairs in consecutive 1..N order.

Stops at Nil: Stops immediately if it encounters a nil entry in the sequence.
Live Interactive Example
Hit Run Code to see it liveIterating Arrays with ipairs
Python 3.12
1
2
3
4
5
Output Console
Click "Run Code" to view the rendered output.
How it works: ipairs yielded 1-based indices 1, 2, 3, 4 with corresponding values.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Find Index of Target Item
Declare `local items = { "apple", "banana", "cherry" }`.
Loop with `ipairs(items)`. If `name == "banana"`, print `"Found banana at index " .. index`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.