lua-users home
lua-l archive

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


Am 17.08.2014 um 20:32 schrieb Dirk Laurie:
2014-08-17 19:08 GMT+02:00 Philipp Janda <siffiejoe@gmx.net>:
Am 17.08.2014 um 17:57 schrieb Dirk Laurie:


I thought of 'pairs' as something provided for the convenience
of idiots like me who do not understand the generic 'for' and
magically provide what is needed. `ipairs`, to me, was similar,
but not really necessary because one could also use the
arithmetic for (I started just as 5.2 reached alpha, so #tbl
was available).

Later, when I started mastering the generic 'for', `pairs` and
`ipairs` became examples of parametrized iterators. I now
think that I understand the generic `for`, so I no longer use
`pairs` and and only the absence of the more basic
ties me to `ipairs`.


But why? The public interface is clearly the iterator constructor (like
`ipairs`) not the iterator triplet -- even if the iterator function in the
specific case of `ipairs` and `pairs` is side-effect free, and the state is
constant and trivial to create. You still use `string.gmatch` and/or
`io.lines`, or do you somehow create the iterator closures by hand?

Why? Because people can override `pairs`, but they can't override
`next`.

Then I probably misunderstood your original post. It sounded like you stopped using `pairs` altogether. I use `next` in for loops myself sometimes when I want raw table iteration. But I wouldn't stop using `[]` in favor of raw[gs]et just because people can override `__index`/`__newindex`.


I do use str:gmatch, yes, but am actually not fond of io.lines,
preferring io.read() inside a loop for greater versatility about
what happens if there is no further line.

And what about all the people who read your code and have
not yet mastered the generic 'for' ...?

People who have not yet mastered the generic 'for' should
spend their time reading PiL Ch.7, not reading my code.

Actually I would go in the opposite direction: Having `rawpairs`
(and maybe `isempty`), I wouldn't miss `next` at all.

This is a question of taste.

Obviously. But as I have written in my last post, `next` makes improving the 'for' loop protocol difficult.


It has such a strange interface anyway

I can't agree. It's a very well thought out and versatile
function. As you so clearly demonstrate, it does the
work of two other functions, and more. It's quite nice
to have in one's __index.

It *does* the job of two other functions, but in an awkward way. I'm pretty sure most Lua-newcomers are puzzled when they see

    for k,v in next,t do ... end
or
    if next(t) == nil then ... end


Did you know that if you say

    for k,v in pairs(tbl) do

Lua will actually check TWICE that tbl is a table?
Apart from explicitly checking whether there is
a metamethod? Which requires a table access?

No I didn't, but Lua will check that `tbl` is a table on every iteration anyway.

Philipp