lua-users home
lua-l archive

Re: AKClassHierarchy

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Feb 12, 2006, at 04:27, Gavin Kistner wrote:
		obj.super.initialize( obj )
Your problem is right there: 'super' cannot be a straight attribute of your object for method dispatch purpose. It needs to be part of your object context instead.
Short illustration:
Given a 'class' function with setup a class hierarchy [1]:
function class( aName, aSuper )
 local aSuper = aSuper or require( "LUObject" )
 local aClass = package.loaded[ aName ]
 if aClass == nil then
 aClass = aSuper:new()
 package.loaded[ aName ] = aClass
 end
 return aClass, aSuper
end
Define a 'Rectangle' class:
local self, super = class( "Rectangle" )
 function self:init( aValue )
 super.init( self, aValue )
 self._value = ( aValue or "?" ):upper()
 print( "Rectangle init" )
 return self
 end
 function self:value()
 return self._value
 end
 function self:testMethod()
return "Rectangle: " .. self:value() .. ": ".. self:class() .. " < " .. self:super()
 end
Define a 'Square' class which extends 'Rectangle':
local self, super = class( "Square", require( "Rectangle" ) )
 function self:init( aValue )
 super.init( self, aValue )
 print( "Square init" )
 return self
 end
 function self:testMethod()
return "Square: " .. self:value() .. ": ".. self:class() .. " < " .. self:super()
 end
And finally define a 'UnitSquare' class which extends 'Square':
local self, super = class( "UnitSquare", require( "Square" ) )
 function self:init( aValue )
 super.init( self, aValue )
 print( "UnitSquare init" )
 return self
 end
 function self:testMethod()
return "UnitSquare: " .. self:value() .. ": ".. self:class() .. " < " .. self:super()
 end
'Rectangle', 'Square' and 'UnitSquare' each invoke their parent 'init' method.
print( "*", require( "Rectangle" ):new( "hello1" ):testMethod() )
print( "*", require( "Square" ):new( "hello2" ):testMethod() )
print( "*", require( "UnitSquare" ):new( "hello3" ):testMethod() )
> Rectangle init
> * Rectangle: HELLO1: Rectangle@1154736 < LUObject@1154352
> Rectangle init
> Square init
> * Square: HELLO2: Square@1155056 < Rectangle@1154736
> Rectangle init
> Square init
> UnitSquare init
> * UnitSquare: HELLO3: UnitSquare@1155600 < Square@1155056
Cheers
--
PA, Onnay Equitursay
http://alt.textdrive.com/
[1] http://dev.alt.textdrive.com/browser/lu/LUObject.lua

AltStyle によって変換されたページ (->オリジナル) /