Menu
CoddyTech

Independent Nested Tables

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

Luau table helpers can make accidental sharing compact. Filling an array with one table value repeats the same reference, not a factory call. Lua 5.1 ports must preserve the intended ownership rather than reproduce that mistake with a shared default. Construct a fresh nested items table inside each object constructor. In the source example, table.create only reserves capacity, and a loop allocates each bag separately. In the target, an ordinary empty array followed by that allocation loop has the same behavior. Duplicate labels remain valid items; counting them is different from implementing a set. The task tests two objects to expose unwanted sharing.

Luau

local bags = table.create(2)
for i=1,2 do bags[i] = {items={}} end
table.insert(bags[1].items, "x")
print(`{#bags[1].items}:{#bags[2].items}`)

Lua 5.1

local bags = {}
for i=1,2 do bags[i] = {items={}} end
table.insert(bags[1].items, "x")
print(#bags[1].items .. ":" .. #bags[2].items)

Porting trap

Moving the items table outside the constructor shares it across all instances, even if each outer instance table is fresh.

challenge icon

Challenge

Easy

Implement bags with an items table and an add(label) method. Input lines are labels added only to the first of two new bags. Return firstCount:secondCount. Empty input is valid.

Edit app.lua, model.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.

Public API checks: Each new bag starts empty. add(label) appends the exact label, keeps duplicates and does not affect another bag. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.

Try it yourself

-- Public API checks
do
local Model=require("model")
local a,b=Model.new(),Model.new()
assert(#a.items==0 and #b.items==0,"new bags start empty")
a:add("x");a:add("x")
assert(#a.items==2 and a.items[1]=="x" and a.items[2]=="x","add preserves labels and duplicates")
assert(#b.items==0,"bag items must be independent")
end
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