Menu
CoddyTech

Table Library Porting

Lesson 11 of 29 in Coddy's Lua for Luau Developers course.

Luau offers table.create to allocate and optionally fill an array. Lua 5.1 needs a constructor or an explicit fill loop. Keep allocation and length separate: an array filled with a value has entries, while reserved capacity alone is not a sequence of that length. One-based indexing, table insertion and removal remain familiar. In a Lua 5.1 port, append at #items + 1 only when the table is dense. Removing a field by assigning nil can create a hole rather than shifting later values. Use table.remove when the intended operation closes a gap.

Luau

local items = table.create(3, "x")
print(table.concat(items, ","))

Lua 5.1

local items = {}
for i = 1, 3 do items[i] = "x" end
print(table.concat(items, ","))

Porting trap

A fill value that is itself a table is shared by all filled positions. Allocate a fresh nested table per position when independent state is required.

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 Luau Developers

Practice on your own: Online Lua compiler