self and Colon Calls
Lesson 22 of 35 in Coddy's Luau for Lua Developers course.
Lua colon receiver insertion transfers exactly. Distinguish method-call colons from the new annotation colon; annotating a parameter does not insert a receiver into a dot call.
Lua 5.1 comparison
local c={n=2}
function c:add(x) self.n=self.n+x end
c:add(3)
print(c.n)Luau behavior
The colon call object:method(x) supplies object as the first argument. A dot call must pass that receiver explicitly. A colon in a parameter annotation is different syntax from a colon method call; neither supplies missing runtime validation.
local c={n=2}
function c:add(x) self.n=self.n+x end
c:add(3)
print(c.n)Expected Luau output:
5Challenge
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.luau, model.luau. The visible locked main.luau 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 Luau for Lua Developers
4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions7Objects and Owned State
Tables as Instancesself and Colon CallsIndependent Instance TablesRecap: Account ObjectsPractice on your own: Online Luau compiler