Lua does not have build in support for OO, but it allows you to build it yourself. Could you please share some of the ways one can implement OO?
Please write one example
This is already answered, but anyway, here's my oop implementation: middleclass.
That lib provides the bare minimum for creating classes, instances, inheritance, polymorphism and (primitive) mixins, with an acceptable performance.
Sample:
local class = require 'middleclass'
local Person = class('Person')
function Person:initialize(name)
self.name = name
end
function Person:speak()
print('Hi, I am ' .. self.name ..'.')
end
local AgedPerson = class('AgedPerson', Person) -- or Person:subclass('AgedPerson')
AgedPerson.static.ADULT_AGE = 18 --this is a class variable
function AgedPerson:initialize(name, age)
Person.initialize(self, name) -- this calls the parent's constructor (Person.initialize) on self
self.age = age
end
function AgedPerson:speak()
Person.speak(self) -- prints "Hi, I am xx."
if(self.age < AgedPerson.ADULT_AGE) then --accessing a class variable from an instance method
print('I am underaged.')
else
print('I am an adult.')
end
end
local p1 = AgedPerson:new('Billy the Kid', 13) -- this is equivalent to AgedPerson('Billy the Kid', 13) - the :new part is implicit
local p2 = AgedPerson:new('Luke Skywalker', 21)
p1:speak()
p2:speak()
Output:
Hi, I am Billy the Kid.
I am underaged.
Hi, I am Luke Skywalker.
I am an adult.