Generalized Iteration
Lesson 7 of 29 in Coddy's Lua for Luau Developers course.
Luau permits a table directly after in in a generic loop. Lua 5.1 requires an iterator function plus its state and control value; ipairs and pairs provide those values. Choose deliberately. For a dense one-based sequence, ipairs yields consecutive integer keys and stops at the first nil. For a dictionary, pairs visits its present keys with no sorted-order promise. Direct Luau table iteration is not a spelling alias for ipairs: a table with holes or noninteger keys needs a contract review before conversion. This exercise receives a dense sequence of input lines and must preserve their order.
Luau
local rows: {string} = {"a", "b"}
for i, value in rows do print(`{i}:{value}`) endLua 5.1
for i, value in ipairs({"a", "b"}) do print(i .. ":" .. value) endPorting trap
Do not replace every direct table loop with ipairs. Dictionary entries would disappear. Sort keys separately when output order matters.
Challenge
EasyEach input line is one nonempty label. Return comma-separated index:label pairs using one-based indexes; return none for no lines.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for Luau Developers
2Flow and Functions
Generalized IterationReplacing continueErasing Type SyntaxPacking Multiple ResultsPractice on your own: Online Lua compiler