Menu
CoddyTech

Tables as Instances

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

C++ constructors initialize an object whose type and member layout are declared ahead of time. Lua has no class declaration or constructor keyword. A constructor is an ordinary function that builds and returns an instance table. Attaching a metatable gives the table shared behavior. The common assignment Item.__index = Item makes missing instance fields look up names on the shared Item table, where methods can live.

C++17

File-scope declarations, with standard headers supplied:

struct Item {
    int n;
    explicit Item(int value) : n(value) {}
};

Inside main, with standard headers supplied:

Item a(2), b(5);
a.n = 8;
std::cout << b.n << '\n';

Lua 5.1

local Item={}
Item.__index=Item
function Item.new(n) return setmetatable({n=n},Item) end
local a,b=Item.new(2),Item.new(5)
print(a.n+b.n)

Porting trap

Keep instance fields in a fresh table created on each constructor call. Returning the prototype itself makes all constructed objects aliases. Attaching a metatable does not automatically invoke an initializer, create declared members, or establish C++ access controls; the constructor function must perform each initialization explicitly.

challenge icon

Challenge

Easy

In model.lua, implement Model.new(n) to create an instance holding n. The app creates two instances from two integer lines and returns their sum.

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: Model.new(n) must retain n on a fresh independent instance. 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(2),Model.new(-3)
assert(a.n==2 and b.n==-3,"Model.new must retain each supplied n")
a.n=9
assert(b.n==-3,"instances must own independent n state")
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