[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Abusing Lua iterators for fun and profit
- From: Philipp Janda <siffiejoe@...>
- Date: Fri, 06 Feb 2015 08:47:05 +0100
Am 06.02.2015 um 08:01 schröbte Dirk Laurie:
2015-02-06 8:22 GMT+02:00 Dirk Laurie <firstname.lastname@example.org>:
Ugh, trying so hard to be precise, and then there's a typo
that totally destroys the point.
One must distinguish between an "iterator function" and an
I think that the separate concept of an "iterator function" is awkward
in Lua anyway. First of all it doesn't need to be a function at all
(e.g. it can be a callable table or userdata). Second, pretty much all
custom iteration in Lua happens in the generic for loop, and the generic
for loop always uses three values. And third, you could always wrap the
three iterator values in a closure to get a single function, so the
only[*] purpose of the current iterator protocol is to allow for a
certain optimization where you can avoid creating a closure for every
loop in some cases. IMHO, optimizations are an implementation detail, so
you should not rely on the presence or absence of any value in an
In my opinion, if an iterator function
I mean "iterator factory".
returns more than one
value, that behaviour should be explicitly documented, since
it relies on a gotcha: something that lexically looks like one
item, but may be more. It's clever, no doubt about that, since
it can be thought of as providing default values that you can
always discard by using parentheses, but it is too clever by
half for my taste.
io.lines and string.gmatch don't do that, so there is no need
to say anything about it.
[*]: I'd rather have it documented whether an iteration can be
restarted at a certain point given only the iterator function, the
state, and the current iteration variable. Because that's the other nice
feature of the current iterator protocol. This is possible for e.g.
`ipairs`, but not `string.gmatch` or `io.lines`.