I never used OOP in lua before. It’s really a noticeable difference when a code language doesn’t handle it for you. I tried to make an event system with inheritance in module script but so far it looks out of place. Is this a general way of doing so? If no, Is there anything I can improve?
--Base Event
Events.Base = {}
Events.Base.new = function()
local Event = {}
Event.DisplayName = "BaseEvent"
Event.Description = "BaseFlair"
function Event:Run()
print("Fired " .. Event.DisplayName)
end
return Event
end
--
--Fireworks
Events["Fireworks"] = {}
Events["Fireworks"].new = function()
local Event = Events.Base.new()
Event.DisplayName = "Fireworks"
Event.Description = "Nice stuff going off"
return Event
end
--
My general strategy is to put all of my “classes” into their own ModuleScripts. Inside the ModuleScripts I create a table that is my “class” that gets instantiated, but I actually return a table that contains all my static members. So something like this:
local Foo = {} -- define a "class"
Foo.__index = Foo -- make this "class" use metamethods
function new() -- A static new method
local self = setmetatable({}, Foo) -- Creates a new table that uses Foo as its metatable
-- Set stuff on self for initialization. This is basically my constructor.
return self -- self is the "instance" of the "class"
end
function Foo:Bar() -- An "instance method"
print("Bar!") -- or whatever else you'd want to do
end
return { -- The actual return object of the ModuleScript
new = new -- Returns the static items, which is usually just new
}
And as far as I can tell, is in line with the RDC video on performance -
Also, the RDC video
In particular, note the field allocation as discussed in the perf video
I have a personal tweak for inheritance for some rare cases, but probably want to avoid that as its not recommended in the style guide and may be poorly supported from a perf point of view.