Instance Methods and self
Define methods using colon syntax and the implicit self parameter.
self is the Instance
When you call obj:method(), Lua passes obj as the first argument automatically. By convention this parameter is named self. Through self, the method accesses instance data and calls other methods.
local Counter = {}
Counter.__index = Counter
function Counter.new(start)
return setmetatable({value=start or 0, step=1}, Counter)
end
function Counter:increment()
self.value = self.value + self.step
end
function Counter:getValue() return self.value end
local c = Counter.new(10)
c:increment(); c:increment()
print(c:getValue()) -- 12Method Chaining
Return self from methods to enable chaining: obj:method1():method2():method3(). Each call returns the same object, allowing a fluent style. This works best for methods that modify state.
local Builder = {}
Builder.__index = Builder
function Builder.new()
return setmetatable({parts={}},Builder)
end
function Builder:add(s) self.parts[#self.parts+1]=s; return self end
function Builder:addAll(t)
for _,v in ipairs(t) do self.parts[#self.parts+1]=v end
return self
end
function Builder:build() return table.concat(self.parts," ") end
local result = Builder.new()
:add("Hello")
:add("from")
:addAll({"Lua","OOP"})
:build()
print(result) -- Hello from Lua OOPAll lessons in this course
- Classes via Metatables
- Constructors and new()
- Instance Methods and self
- Encapsulation with Closures