lua-users home
lua-l archive

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


On Mon, 24 May 2010, Jonathan Castello wrote:

Okay, so this isn't quite at the level of detail I was hoping for, but 
close enough. :)

>   local obj_meta = getmetatable(object)
>   if type(object) == "number" and
[snip number case]
>   else
>     local f, s, var
>     if obj_meta.__iter then
>       f, s, var = obj_meta.__iter(obj, params)
>     elseif type(object) == "table" then
>       f, s, var = pairs(obj, params)
>     end
>   end

This particular generic-for proposal doesn't work for basic iterators 
which follow the current iterator protocol.  For example, it would try 
to run pairs() on the function "next" if we were to give it this:

for k,v in next, sometable do
	print(k,v)
end

In lua 5.1 that's equivalent to "for k,v in pairs(sometable) do 
print(k,v) end".

> Yes; that's why I qualified it before as "a number without an __iter".
> I wouldn't expect the VM to handle cases like that, but I doubt
> there's a good reason to change __iter on a number anyways, so you're
> not going to have many cases where the VM can't optimize a numeric
> iteration.

The key point is that the _compiler_ can't know in advance whether 
you're going to give numbers some wacky __iter metamethod before you 
actually run the loop, so you're going to have to check for __iter on 
numbers every time you begin a loop, just like in your pseudocode 
above.  By the time the interpreter wants to run your loop it's too 
late to do any optimisation.

Joonas