lua-users home
lua-l archive

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



On Mar 03, 2007, at 16:11, gary ng wrote:

how can I easily define a method a.foo which is
equivalent to this :

usually you will need to keep track of your super class, look up the method implementation and pass self to it, e.g.:

function self:doIt()
        return super.doIt( self ) .. " well"
end

Here is an example, using the module package:

local function extends( aSuper )
        return function( aClass )
                setmetatable( aClass, aSuper )
                aClass.__index = aClass

                aClass.self = aClass
                aClass.super = aSuper

                if aClass.initialize then
                        aClass:initialize()
                end

                return aClass
        end
end

local class = module

-- define the root class
class( "Object", extends(), package.seeall )

function self:initialize()
        print( "initialize", self:className() )

        return self
end

function self:new( ... )
        local anObject = {}
        local aClass = self:class()

        setmetatable( anObject, aClass )

        return anObject
end


function self:class()
        return self._M
end

function self:className()
        return self._NAME
end

function self:this()
        return self
end

function self:superclass()
        return self.super
end

function self:value()
        return 1
end

function self:doIt()
        return "do it" .. self:value()
end

-- define a subclass
class( "MyObject", extends( Object ) )

function self:value()
        return 2
end

function self:doIt()
        return "about to " .. super.doIt( self )
end

print( self:className() )

-- define a another subclass
class( "MyOtherObject", extends( MyObject ) )

function self:value()
        return 3
end

function self:doIt()
        return super.doIt( self ) .. " well"
end

local AnotherObject = require( "Object" )

print( 1, AnotherObject:className() )
print( 2, AnotherObject:doIt() )

print( 3, self:doIt() )
print( 4, self:this():superclass():superclass():className() )
print( 5, self:class():className() )

print( 6, self )
print( 7, self:class() )
print( 8, self:new():className() )
print( 9, self:new():doIt() )

> 1       Object
> 2       do it1
> 3       about to do it3 well
> 4       Object
> 5       MyOtherObject
> 6       table: 0x104af0
> 7       table: 0x104af0
> 8       MyOtherObject
> 9       about to do it3 well