[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Let's talk about __call
- From: Phil Leblanc <philanc@...>
- Date: Fri, 22 Jul 2016 18:43:08 -0400
On Fri, Jul 22, 2016 at 3:48 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> I use a minimal object-oriented paradigm in which the method
> table is also the __index and the constructor.
Same here:
class = {
__call = function(c, t)
local obj = setmetatable(t or {}, c)
if c == class then obj.__index = obj end
return obj
end
}
setmetatable(class, class)
-- Let's use 'class' to define new classes:
list = class()
-- Let's define some list methods
list.append = function(t, elem) t[#t+1] = elem ; return t end
list.remove = table.remove
-- Now, for a second use of __call(), let's define a list iterator:
local inext = ipairs{}
list.__call = function(l, x, i) return inext(l, i or 0) end
-- ... and use it:
mylist = list{11, 22, 33}
for idx, value in mylist do print(idx, value) end