lua-users home
lua-l archive

Re: idea: __iter generic-for metamethod

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


Going from a post Joonas just made, it should actually read like this:
A for statement like
 for var_1, ···, var_n in explist do block end
is equivalent to the code:
 do
 local f, s, var = explist
 --proposed addition
 if type(f)~= "function" and not metatable(f).__call then
 local meta_f = metatable(f).__iter
 if not meta_f and type(f)=="table" then meta_f = pairs
 if meta_f then f, s, var = meta_f(f) end
 end
 while true do
 local var_1, ···, var_n = f(s, var)
 var = var_1
 if var == nil then break end
 block
 end
 end
(I'd forgotten that __call could be used to replicate the non-factory version of __iter.) On 2010年5月24日 17:06:09 -0700, Stuart P. Bentley <stuart@testtrack4.com> wrote:
On 2010年5月24日 16:53:32 -0700, Jonathan Castello <twisolar@gmail.com> wrote:
I wrote your algorithm into a usable Lua function to try it out. I had
to add a check for nonexistent metatables, but it does work.
 From the manual:
"The code shown here in Lua is only illustrative; the real behavior is hard coded in the interpreter and it is much more efficient than this simulation. All functions used in these descriptions (rawget, tonumber, etc.) are described in §5.1. In particular, to retrieve the metamethod of a given object, we use the expression
 metatable(obj)[event]
This should be read as
 rawget(getmetatable(obj) or {}, event)"

AltStyle によって変換されたページ (->オリジナル) /