I am trying to make a simple api that eases the process of creating classes and sub-classes.
function newClass(index,...)
local new_class = {}
setmetatable(new_class,{__index = index})
local optionalArgs = {...}
if optionalArgs[1] ~= nil then
setmetatable(new_class,optionalArgs[1])
end
return new_class
end
--TESTINGCODE
exampleSuper = newClass({name="Super",id=1,getName = function() print("Super") end,})
exampleSuper.getName()
exampleSub = newClass({name="Sub",},exampleSuper)
print(exampleSub.id)
The problem is that even though I create a new super class called exampleSuper, it's fields aren't given to the exampleSub class. How can I change my code to allow my function to define a sub class?
This question is well answered in Object-Oriented Programming chapter of Programming In Lua, specifically in the Inheritance section.
In your particular case, when optionalArgs[1] ~= nil
check is true, you don't set __index
in the metatable as you overwrite your earlier assignment.
Something like this, maybe:
function newClass(new_obj,old_obj)
old_obj = old_obj or {} --use passed-in object (if any)
new_obj = new_obj or {}
assert(type(old_obj) == 'table','Object/Class is not a table')
assert(type(new_obj) == 'table','Object/Class is not a table')
old_obj.__index = old_obj --store __index in parent object (optimization)
return setmetatable(new_obj,old_obj) --create 'new_obj' inheriting 'old_obj'
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With