lua-users home
lua-l archive

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


On Sun, Nov 15, 2009 at 01:00:20PM -0500, Jim Pryor wrote:
> If you want inheritance, you can wrap that in too. You're just giving up
> the object-oriented syntax; you don't have to give up its power.
> 
> -- One way to get inheritance
> 
> local class_sentinel = {}
> 
> setmetatable(Set, {__call = function(cls, ...)
>     local obj = {}
>     for i=1,select('#',...) do
>         obj[select(i,...)] = true
>     end
>     obj[class_sentinel] = cls
>     return setmetatable(obj, Set)
> end
> local function _intersection(self, other)
>     local cls = self[class_sentinel]
>     -- we assume that subclasses will have their bases as __index, so
>     -- cls.intersection is always defined, even though it may just
>     -- be == Set.intersection
>     local meth = cls.intersection
>     if meth ~= _intersection then
>         return meth(self, other)
>     else
>         -- default Set.intersection implementation here --
>     end
> end
> Set.intersection = _intersection

Or:

setmetatable(Set, {__call = function(cls, ...)
    local obj = {}
    for i=1,select('#',...) do
        obj[select(i,...)] = true
    end
    return setmetatable(obj, cls)
end
local function _intersection(self, other)
    -- this relies on public metatables
    local cls = getmetatable(self)
    local meth
    if cls ~= Set then meth = cls.intersection end
    if meth and meth ~= _intersection then
        return meth(self, other)
    else
        -- default Set.intersection implementation here --
    end
end
Set.intersection = _intersection

-- 
Profjim
profjim@jimpryor.net