lua-users home
lua-l archive

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


I just realised that, to quote the late GW Bush, I missunderestimated the
__call trick. I have been using this for some time:

meta = {__call=function(o) return pairs(o) end}
tab = {"Rio", "London", "Berlin"}
setmetatable(tab, meta)
for _,v in tab() do print(v) end

And I understood from earlier postings that I could leave out the empty
parenthesis in this case. I just tried that for the first time, but it does
not work - gives an infinite loop. I now see the case is different with and
without the iteration but both do a valid call. Without the parenthesis, the
object will be "called" repeatedly during the iteration rather than once to
set it up.

I tried modifying it like this:

meta = {__call=function(o,i) return next(o,i) end}
tab = {"Rio", "London", "Berlin"}
setmetatable(tab, meta)
for _,v in tab do print(v) end

But now it prints "Rio" endlessly and the iteration does not advance. Can
someone please show me the code to make this second case work?

I do now understand that Lua currently only recognises a function (or
method) call if the empty parenthesis is present (or a string or table
literal is used in its place) and that this behaviour is consistent. I
understand that the empty parenthesis case can only mean one thing and if it
is already earmarked for something else it cannot mean "call with no
parameters".

I guess I am back to favouring this one:

meta = {pairs=function(o) return pairs(o) end; ipairs=function(o) return
ipairs(o) end}
meta.__index = meta
tab = {"Rio", "London", "Berlin"}
setmetatable(tab, meta)
for _,v in tab:pairs() do print(v) end
for _,v in tab:ipairs() do print(v) end

Which lets you decide what iterator(s) to provide for each class and what to
name them, but requires the empty parenthesis.

> -----Original Message-----
> From: lua-bounces@bazar2.conectiva.com.br [mailto:lua-
> bounces@bazar2.conectiva.com.br] On Behalf Of Roberto Ierusalimschy
> Sent: 14 September 2009 13:35
> To: Lua list
> Subject: Re: Regarding the name 'pairs'
> 
> > So, is there some support for Mark Hamburg's closure sugar in Rio ;)
> ?
> 
> Yes. Here we would write  C(set, "values") for C:values  and define C
> as
> 
>   C = function (obj, met)
>         met = obj[met]
>         return function (...) return met(obj, ...) end
>       end
> 
> (I guess it works in other cities too ;)
> 
> -- Roberto