lua-users home
lua-l archive

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


Sven Olsen <sven2718 <at> gmail.com>

>One more little question about the self-iterating patch.  I found this line in the patch notes:

>This will break some subtle code tricks such as using the __call event to "fake" self-iteration.

 

>This certainly sounds like something all patch users should keep in mind, but I don't understand what >sorts of "subtle tricks" are being referenced.

 

Before I implemented this patch I used to do:

 

tab = {"John","Hind"}

setmetatable(tab, {__call=pairs})

for k,v in tab() do print(k,v) end

 

I thought this would be broken (it may have been in earlier Lua versions) but re-testing it today it seems to be fine. To maintain compatibility, I test the type of the first of the three parameters of the generic for opcode. If it's a function I proceed with the original code, otherwise I look for the '__iter' metamethod. The original code does not check the parameters, it just launches into the first iteration which fails if the first parameter cannot be called. So the difference is between 'being callable' and 'being a function'. I think you'd need to have a 'pairs' analog which returned a 'next' analog that was a callable object but not a function to break it - I cannot think of a reasonable usage case for that. My caveat may be over-cautious!