Menu
CoddyTech

self and Colon Calls

Lesson 34 of 48 in Coddy's Lua for GDScript Developers course.

GDScript member calls pass the current instance automatically, so a method can use self or access its fields directly. Lua represents methods as table functions. Defining function Counter:add(delta) inserts an initial parameter named self; calling counter:add(3) passes the receiver in that position. The equivalent explicit call is Counter.add(counter, 3). A dot call does not insert the receiver. The shared function can therefore update whichever instance was passed to it. Keep the constructor convention separate: a function declared as Counter.new(initial) expects only the initial value unless you deliberately design a different signature.

GDScript 4

extends SceneTree
class Counter:
    var n = 5
    func add(delta):
        self.n += delta
        return self.n
func _init():
    var counter = Counter.new()
    print(counter.add(3))
    print(counter.n)
    quit()

Lua 5.1

local Counter = {}
Counter.__index = Counter
function Counter:add(delta)
  self.n = self.n + delta
  return self.n
end
local counter = setmetatable({n = 5}, Counter)
print(counter:add(3))
print(counter.n)

Porting trap

Replacing every GDScript dot with a Lua dot loses the receiver on instance methods. Use a colon call or pass the instance explicitly.

challenge icon

Challenge

Easy

Model.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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for GDScript Developers

Practice on your own: Online Lua compiler