'OOP' in Lua

23 May 2019
-- Class definition
-- -> The attributes in curly braces are redunant, 
--    since we explicitly set them inside the constructor. 
--    I still include them. For brevity and convenience.
local Person = {name = nil, age = 0}
-- Re-route instance table lookups to the class table, to get methods.
-- -> Otherwise, we'd have to do "Person.__index.new(..)" 
--    rather than "Person.new(..)".
Person.__index = Person

-- Constructor method
function Person.new(name, age)
local self = setmetatable({}, Person)
self.__index = self
self.name = name or nil
self.age = age or 0
return self
end

-- Derived class method "greet()"
function Person.greet(self)
print("Hello, " .. self.name .. "!")
end

-- Object "henry" is an instance of class "Person".
henry = Person.new("Henry", 25)
-- Access class property "age".
print("Age: " .. henry.age)
-- Call class method "greet()".
henry:greet()

dorothy = Person.new("Dorothy", 68)
print("Age: " .. dorothy.age)
dorothy:greet()