OOP code including inheritance, thoughts?

I made this very late in the night, it’s basically just an item framework, but I will not be able to edit this code for a while so if people can review it so I can fix any problems or bad habits it may have and improve it I will be very happy and that would save me a lot of time, I will drop the two modules I made and the other module that handles the data. (made two modules that use OOP and inheritance and another that holds data)

ItemData,ItemClass and ResourceClass(both item classes)

If you find any of the problems mentioned above pls let me know! And thank you in advantage.

1 Like

There can be a few improvements made to your code. First, I like how you append all the functions in the table while declaring and initializing it, which prevents rehashing the table unnecessarily.

You should name all the classes via PascalCase and define the variables that require modules to have the exact same name as the module. Functions should also be named via PascalCase. Variables not being used should be named as _ to show the reader that they aren’t being used.

function resource.new(amount)
    local item = superclass.new(amount)
    local interface = {
        __index = function(t, k)
            return item[k] or resource[k]
        end,
        __newindex = function(t, k, v)
            item[k] = v
        end,
        __tostring = function(t)
            return tostring(item)
        end,
    }
    local self = setmetatable({}, interface)
    
    self.class = "resource"
    self.name = "wood"
    
    self.amount = amount or self.maxAmount
    
    return self
end

Can be changed to:

function Resource.new(amount)
    local item = superclass.new(amount)

    local InterfaceMeta = {
        __index = function(_, k)
            return item[k] or resource[k]
        end,

        __newindex = function(_, k, v)
            item[k] = v
        end,

        __tostring = function()
            return tostring(item)
        end,
    }

    return setmetatable({

      Class = "Resource",
      Name = "Wood",
      Amount = amount 
    
    }, InterfaceMeta)
    
end
1 Like