Menu
CoddyTech

Arrays to Dense Tables

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

A C array has fixed storage, and a separate length commonly records how much of that storage is in use. Removing an element requires shifting later values and updating that length. A Lua table can represent a growable sequence using consecutive integer keys starting at one. table.insert appends by default, while table.remove shifts entries after a removal. table.concat joins a sequence of strings with a separator. The C example removes array index one; the Lua example removes table index two. Both operations remove the second element.

C

#include <stddef.h>
#include <stdio.h>
int main(void) {
    const char *items[] = {"a", "b", "c"};
    size_t length = sizeof items / sizeof items[0];
    for (size_t i = 1; i + 1 < length; ++i) {
        items[i] = items[i + 1];
    }
    --length;
    for (size_t i = 0; i < length; ++i) {
        printf("%s%s", i == 0 ? "" : ",", items[i]);
    }
    putchar('\n');
    return 0;
}

Lua

local items = {"a", "b", "c"}
table.remove(items, 2)
print(table.concat(items, ","))

Porting trap

Assigning nil directly deletes a key without shifting later entries. A table with holes is not a dense sequence, and #items is not a reliable count of all its stored values.

challenge icon

Challenge

Easy

Input lines are labels. Remove the first label when present, append done, then return the labels joined by commas.

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