self and Colon Calls
Lesson 34 of 48 in Coddy's Lua for PHP Developers course.
PHP instance methods receive $this implicitly through the object call syntax. Lua colon syntax is shorthand for passing a receiver: object:add(3) becomes object.add(object, 3). Defining function Model:add(x) similarly inserts a first parameter named self. Dot calls do not supply a receiver. Use colon consistently for methods and dot for ordinary module functions whose signatures do not expect self. Lua does not check this distinction for you before the call.
PHP
<?php
class Counter {
public int $n = 2;
public function add(int $x): void { $this->n += $x; }
}
$c = new Counter();
$c->add(3);
echo $c->n, "\n";Lua
local c={n=2}
function c:add(x) self.n=self.n+x end
c:add(3)
print(c.n)Porting trap
Changing a PHP arrow call to a Lua dot call without adding the receiver shifts every argument. The resulting error may appear in arithmetic inside the method, even though the real mistake is at the call site.
Challenge
EasyModel.new(n) stores n. Implement Model:add(delta), updating n and returning it. Input has initial n followed by one delta. The app invokes the colon method and returns its result.
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) stores independent n state. add(delta) returns and stores the updated n, including negative and zero deltas. 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(10)
assert(a:add(3)==5 and a.n==5,"add must return and store the updated n")
assert(a:add(-7)==-2 and a:add(0)==-2,"add must support negative and zero deltas")
assert(b.n==10,"add must not mutate another instance")
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