OOP is pretty easy to mess up

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
        --
2 Likes

Is there a reason you’re not using any metamethods?

Can be made like this:

local Events = {}
Events.__index = Events

function Events.new(displayName, description)
   local self = setmetatable({}, Events)
   self.DisplayName = displayName
   self.Description = description
   return self
end

function Events:Run()
   print("Fired " .. self.DisplayName)
end

Test

local ev = Events.new("bruh", "bruh moment")
ev:Run()

Here's a link to a thread where you can learn about object-oriented programming (OOP):

4 Likes

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
}

Looks way less clean, but if it’s the right way do to so I’m not to argue
tnx much

P.S Mainly because I’d have a set of fixed events within a module I can easily grab from anywhere, instead of constructing them at need.

1 Like

I generally follow the style guide
https://roblox.github.io/lua-style-guide/#prototype-based-classes

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.

1 Like