chaining constructors across derived classes
Example of building class hierarchy in Lua.
Unlike C++, chaining constructor functions must be written explictly.
-- Produces 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 "instance table" from "class table" (metatable).
-- For use in 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 root base class can begin with empty table
-- ctor.
function Base:new( name )
-- If base class is being instantiated, base class will be passed as self.
-- Or, 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 "class table" that inherits from another "class table".
-- Derived becomes 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