lua-users home
lua-l archive

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


> Date: Mon, 25 Nov 2013 10:03:56 +0000
> From: Kevin Martin <kev82@khn.org.uk>
> Subject: Re: table library changes (was Re: table.new in 5.3?)

> Not sure I agree with this entirely. The greatest thing about ipairs
> for me is that it lets you just loop over the entries in order without
> worrying about the index. If you have a few nested loops, where you
> don't care about the index in any of them, just the array entry, then
> saying:
>
> for _, o1 in ipairs(t) do
>
> is a lot nicer, and less error prone than
>
> for o1_i=1,#t do local o1 = t[o1_i]

The need for that dummy variable to receive the index rather spoils the 'niceness' IMHO!
If I were implementing lists without OO, I'd want to write my own iterator factory, so we could write:

for element in elements(list) do

Why privilege the one specific case 'ipairs' does - what about indexing the list in reverse, or between two limits? Pretty soon you are falling back on numeric 'for' anyway because 'ipairs' does not do exactly what you want.

> In regards to the metamethod, I've never needed it personally, but
> isn't it there for cases where t[i] is a very expensive operation, but
> iteration can be done much cheaper. Say for example
>
> 1) Iterating over a linked list (__ipairs can cache the current node)
> 2) Where the data for t[i] is accessed over a network (__ipairs can
> fetch it in bulk because it knows it's iterating)

These are certainly good cases for specialised iterators, but why implement them by hijacking 'ipairs'? Again, write your own iterator factory and call it something appropriate.

What I have done in my own powerpatch allows the list example to be simplified even further to:

for element in list do

This works because 'list' has a metatable which supplies the appropriate iterator factory for tables specialised as lists. Instead of 'pairs' and 'ipairs' metamethods, I just have 'iter', so generic 'for' does not have to distinguish between two different types of iteration (but if needed, you can still provide multiple iterator factories, ideally as methods).



---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com