Menu
CoddyTech

Array Loops to ipairs

Lesson 14 of 48 in Coddy's Lua for C Developers course.

A C array loop usually carries an explicit element count and starts indexing at zero. A dense Lua sequence conventionally stores its first element at key one. The iterator ipairs supplies both the index and the value for successive integer keys. The examples label two strings with one-based positions; C adds one when displaying its zero-based index.

Lua tables do not store a separate declared array bound. ipairs stops at the first missing integer key, even if larger keys exist. Keep sequences dense when their traversal depends on this iterator. A stored false value is still an element and does not stop iteration. Named fields require a different traversal strategy.

C

#include <stdio.h>

int main(void)
{
    const char *labels[] = {"a", "b"};
    size_t count = sizeof labels / sizeof labels[0];
    for (size_t i = 0; i < count; ++i) {
        printf("%zu:%s\n", i + 1, labels[i]);
    }
    return 0;
}

Lua

local labels = {"a", "b"}
for i, value in ipairs(labels) do
  print(i .. ":" .. value)
end

Porting trap

Do not copy a C zero-based access directly into a Lua sequence. Avoid using ipairs on sparse data, because a missing key ends traversal rather than being skipped.

challenge icon

Challenge

Easy

Each 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))
quiz iconTest yourself

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

All lessons in Lua for C Developers

Practice on your own: Online Lua compiler