 |
Chaining Constructors Across Derivative Classes
This is an example of building a class hierarchy in Lua.
Unlike C++, chaining constructor functions has to be done explictly.
-- Produces a metatable (class table) that inherits methods from another one.
function lib.DerivesFrom( BaseMT, t )
local t = t or {}
setmetatable( t, BaseMT )
BaseMT.__index = BaseMT
return t
end
-- Produces an "instance table" from a "class table" (metatable).
-- For use in a Class:new() method.
function lib.NewInstance( classTable, argTable )
-- Construct instance table.
local instance = argTable or {}
setmetatable( instance, classTable )
classTable.__index = classTable
return instance
end
Base = { } -- ONLY THE ROOT BASE CLASS CAN BEGIN WITH AN EMPTY TABLE
-- ctor.
function Base:new( name )
-- If base class is being instantiated, the base class will be passed as self.
-- Or, the derivative is being instantiated, which chains ctors by passing its instance as self.
if ( self == Base ) then
self = lib.NewInstance( Base ) -- not chained, need new instance
end
self.name = name
return self
end
-- lib.DerivedClass() produces a "class table" that inherits from another "class table".
-- Derived becomes a metatable, inheriting from Base, from which instance tables can be produced.
Derived = lib.DerivesFrom( Base )
function Derived:new( name, value )
-- Make instance table from derived metatable.
if ( self == Derived ) then
self = lib.NewInstance( Derived )
end
Base.new( self, name ) -- chain to parent's ctor
self.value = value -- derivative-specific
return self
end
|
|