Construct Table Instances
Lesson 33 of 48 in Coddy's Lua for C Developers course.
A C factory can return a struct by value. Each receiving variable then contains its own scalar fields. In Lua, a constructor is an ordinary function that creates and returns a table. Attach a shared metatable with setmetatable, then set its __index field to the shared prototype to provide fallback lookup. Instance data belongs in the fresh table, while shared behavior can live on the prototype. The two constructors below create independent values initialized with different counts.
C
#include <stdio.h>
struct Item { int n; };
static struct Item item_new(int n)
{
struct Item item = {n};
return item;
}
int main(void)
{
struct Item a = item_new(2);
struct Item b = item_new(5);
a.n = 8;
printf("%d:%d\n", a.n, b.n);
return 0;
}Lua
local Item = {}
Item.__index = Item
function Item.new(n)
return setmetatable({n = n}, Item)
end
local a, b = Item.new(2), Item.new(5)
a.n = 8
print(a.n .. ":" .. b.n)Porting trap
Returning the prototype itself would give every caller the same table. Unlike assigning a C struct value, assigning a Lua table to another variable copies a reference. Allocate a new instance table on every constructor call.
Challenge
EasyIn 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for C Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions7Objects and Owned State
Validate Before MutationConstruct Table InstancesReceiver Arguments and ColonOwn Each Nested TableRecap: Account Objects2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission RulesPractice on your own: Online Lua compiler