lua-users home
lua-l archive

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



On Nov 29, 2006, at 19:54, Sam Roberts wrote:

Does anybody have any links to such an OO library?

Nope. But you could roll your own :)

For example, using the module function:

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:itself()
        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:itself():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

Cheers,

PA.