[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: New metamethod for method lookup
- From: Jim Pryor <lists+lua@...>
- Date: Sun, 15 Nov 2009 13:29:29 -0500
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