lua-users home
lua-l archive

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


100 in this numeric for example wouldn't be an iterator function. All parameters here would have a completely different meaning, than in usual for-in. It's better to have two different semantics, each with its own strict meaning. Current numeric for semantics is also much clearer.

I like the __iter thing. Here's how I see it:
1) Ignore __call meta-method in the 'for' statement and use __iter instead.
2) Get rid of __pairs and make 'pairs' absolete.
So, "pairs(t)" turns into "t", "__pairs" turns into "__iter".
"for k, v in t do" will call __iter if it's present or traverse the table as pairs(t) currently does.
This may also allow optimization of traversal.

On 25.05.2010 2:27, Jonathan Castello wrote:
I posted an idea a few days ago that I didn't hear back much about, so
I thought I'd explain it a little more. I think it's at least an
"interesting" idea, and I'd like to hear what people think about it.
[1] [2]

Instead of moving towards more numeric-for usage, we can abolish it
entirely in favor of an __iter metamethod, with a default one set for
numbers. You would use "for i in 100, 1, -1 do" instead of "for i=100,
1, -1". And it would be very easy to attach an ipairs-like function as
a table's __iter, or use an ipairs() in the loop so "for k,v in
ipairs(t) do" still works.

The basic semantics of this would be: the variables on the left of
"in" are the same as before, the return values per iteration. The
first value on the right side is the object to iterate over; __iter is
checked first, and if it doesn't exist, attempt to call it as a
function. If it succeeds, attempt to call its return value. All values
on the right side of the "in" should be passed to the object's
__iter/__call (including the object). I don't think anything would
change in regards to iterator factories, although "for k,v in
myiter(t) do" would be equivalent to "for k,v in myiter, t do". (Well,
almost. If functions have an __iter metamethod, that would be used
instead of calling it. But that's not a very useful thing to do.)

A table's default iterator would be pairs(), which is used if there is
no __iter set for that table. This lets you do "for k,v in t do", and
you can change the semantics/ordering of your particular iteration at
a stroke if you set __iter in just the one place. This rather vividly
reminds me of the gem "Effecting Large-Scale Change (with little
trauma) using Metatables", from Lua Programming Gems.

Please let me know what you think, I'd really appreciate it.
~Jonathan

[1] http://lua-users.org/lists/lua-l/2010-05/msg00576.html
[2] http://lua-users.org/lists/lua-l/2010-05/msg00582.html




--

___________________________________________
Best regards,
Sergey Rozhenko                 mailto:sergroj@mail.ru