[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Implementing "super()" for classes
- From: Aaron MacDonald <aaronjm@...>
- Date: Fri, 07 May 2010 16:15:33 -0300
I have a lightweight object orientation module. It's centred around this "createClass" function:
function createClass(base)
local newClass = {} -- Contains class methods
local classMeta = { __index = newClass }
if base
then
setmetatable(newClass, { __index = base })
end
-- Object creation is assumed to be Objective C style.
-- Classes are expected to have an "init" method for
-- initializing its variables.
--
-- object = Class.new()
-- object:init(data1, data2, ... dataN)
function newClass.new()
local instance = {}
setmetatable(instance, classMeta) -- "instance" may access
-- class methods
return instance
end
return newClass
end
I would define and use classes like this:
MyClass = createClass()
-- The "constructor"
function MyClass:init(data)
self.data = data
end
function MyClass:printData()
print(self.data)
end
object = MyClass.new()
object:init('Hello')
object:printData()
My issue is that I am unsure how to implement a "super" construct for accessing an object's superclass methods. Ideally I'd be able to do something like this:
MySubclass = createClass(MyClass)
function MySubclass:init(data, extraData)
self:super():init(data)
self.extraData = extraData
end
function MySubclass:printData()
self:super():printData()
print(self.extraData)
end
"self:super()" would, I assume, return a table with the object's data but with the functions of the superclass. Could this be accomplished by making a copy of the object table and setting its metatable to the base class table?