Lua inheritance
I am trying to make a simple api that makes it easier to create classes and subclasses.
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 if I create a new superclass called exampleSuper, its fields are not assigned to the exampleSub class. How can I change my code so that my function can define a subclass?
source to share
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
source to share
This question is well answered in the chapter "Object Oriented Programming" in Lua , in particular Inheritance .
In your specific case, when the validation is optionalArgs[1] ~= nil
correct, you are not setting __index
in the meta, as you are overwriting the earlier assignment.
source to share
The newClass
second call setmetatable
just overwrites the first. The following shorter function will give you the expected behavior:
function newClass(new_class, super)
new_class = new_class or {}
-- This assumes single inheritance. Multiple inheritance would require a
-- function for __index.
if super then
setmetatable(new_class,{__index = super})
end
return new_class
end
source to share