Independent Instance Tables
Lesson 35 of 48 in Coddy's Lua for PHP Developers course.
PHP array properties initialized for each object behave independently, while a static property belongs to the class. Lua prototypes similarly share fields placed on the prototype table. Create each mutable items table inside the factory and store it on the instance. Otherwise several objects can discover and mutate the same prototype-owned collection through __index. A new outer table is not enough if its nested table was allocated only once outside the factory.
PHP
<?php
class Bag {
public array $items = [];
public function add(string $label): void { $this->items[] = $label; }
}
$a = new Bag();
$b = new Bag();
$a->add("x");
echo count($b->items), "\n";Lua
local function bag() return {items={}} end
local a,b=bag(),bag()
table.insert(a.items,"x")
print(#b.items)Porting trap
PHP array copy-on-write can hide sharing assumptions that become visible when ported to Lua tables. Check ownership at every mutable level. An object should not gain another object's items merely because both use the same methods.
Challenge
EasyImplement 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for PHP Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions7Objects and Owned State
Validation Before MutationTables as Instancesself and Colon CallsIndependent Instance TablesRecap: Account Objects2Values and Decisions
Null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler