Menu
CoddyTech

Own Each Nested Table

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

A C struct can embed an array directly, giving each struct value separate array storage. If it instead holds a pointer, two structs may point at shared storage, so allocation and ownership require more care. A Lua table field holding another table behaves like a reference, even when the outer tables are different. Allocate the nested items table inside the constructor to give each bag independent mutable contents. The C example uses a small embedded array; the Lua example uses a fresh sequence for each bag.

C

#include <stdio.h>
#include <stddef.h>
struct Bag { const char *items[4]; size_t count; };
static struct Bag bag_new(void)
{
    struct Bag bag = {{NULL}, 0};
    return bag;
}
int main(void)
{
    struct Bag a = bag_new();
    struct Bag b = bag_new();
    a.items[a.count++] = "x";
    printf("%zu:%zu\n", a.count, b.count);
    return 0;
}

Lua

local function bag_new()
  return {items = {}}
end
local a, b = bag_new(), bag_new()
table.insert(a.items, "x")
print(#a.items .. ":" .. #b.items)

Porting trap

A fresh outer table does not guarantee independent nested state. Putting one items table on a shared prototype makes every instance find the same collection. Construct two instances, mutate one, and check that the other remains empty.

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

Practice on your own: Online Lua compiler