lua-users home
lua-l archive

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



On Sep 16, 2007, at 09:01, Daniel Collins wrote:

This is pretty much your option three. The advantage is that by using
the prototype (or class table) as the metatable for class instances, you don't require the additional table per instance. It also works well with
inheritance, as described in PiL.


FWIW, I pretty much given up on OO in Lua, but during my OO period I settled for PiL's approach as well:

http://www.lua.org/pil/16.1.html


The base class does something along these lines:

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

        setmetatable( anObject, aClass )

        return anObject:init( ... )
end

http://dev.alt.textdrive.com/browser/lu/LUObject.lua


And subclasses are defined like this:

-- define the class
local super = LUObject
local self = super()

-- method for initialization
function self:init( aContent, aMode )
        self = super.init( self )

        if aMode ~= nil then
                setmetatable( self:content(), { __mode = aMode } )
        end

        self:addAll( aContent )

        return self
end

http://dev.alt.textdrive.com/browser/lu/LUList.lua


But... I don't bother with any of this anymore and simply use a combination of module and metamethods instead, e.g.:

module( 'URL' )
_VERSION = '1.0'

local self = setmetatable( _M, {} )
local meta = getmetatable( self )

function meta:__call( aValue )
    return NewURL( aValue )
end

function self:__add( aValue )
    return AddURLs( self, NewURL( aValue ) )
end

function self:__concat( aValue )
    return tostring( self ) .. tostring( aValue )
end

function self:__eq( aValue )
    return tostring( self ) == tostring( aValue )
end

function self:__lt( aValue )
    return tostring( self ) < tostring( aValue )
end

function self:__tostring()
    return WriteURL( self )
end

http://dev.alt.textdrive.com/browser/HTTP/URL.lua