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:

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( ... )

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 } )

        self:addAll( aContent )

        return self

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 )

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

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

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

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

function self:__tostring()
    return WriteURL( self )