lua-users home
lua-l archive

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


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`.

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.

> 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.

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?