Help with Composition OOP for making a gun

Hey so I am currently trying to make a gun in roblox using OOP but with composition. I don’t really know how I should go about it since my current methods does not have a good way to do this. I used to make the guns out of inheritance but I have a feeling that using composition is going to pay off more in the long run. Do you guys know how to do this or have any good resources?

What classes are you planning on using? Are you planning on assembling it with something like a magazine class, a bullet class, and a gun class? If so you can just store the other objects inside the actual gun class itself. You can see the example used here:

Alright I’ll test this method real quick and let you know how it goes. Also by making components inside of this object, is there a way to pass the main object into the components?

It is possible as long as you don’t call the .new constructor from the class and only use the other methods. It really depends on how you set up your module scripts. Some people set theirs up like so:

local module = {}
module.__index = module

-- Constructor
function module.new()
    local object = setmetatable({}, module)

    self.text = "Hello World"

    return object
end

-- Example method
function module:method(text)
    self.text ..= " " .. text
end

return module

Others like myself prefer to only return a table that list the constructors of the objects to avoid letting the objects act like constructors themselves. This is shown like this:

local module = {}
module.__index = module

-- Example method
function module:method(text)
    self.text ..= " " .. text
end

return {
    new = function() -- This is the constructor
        local object = setmetatable({}, module)

        self.text = "Hello World"

        return object
    end
}

This means that if you use the first approach you probably will be able to do this. However, if you use the second approach then probably not. However, I fail to see the usefulness of this.

1 Like