Re: Why does numeric for loop not accept an explist?
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: Why does numeric for loop not accept an explist?
- From: Duck <duck@...>
- Date: Tue, 1 Jan 2008 14:37:34 +1100 (EST)
However, numeric for loops are restricted to an explicit argument
list, so the first example won't compile:
function indicies(t) return 1, #t end
for key = indicies(t) do
print(key, t[key])
end
[snip]
The complete syntax does not give the reason for this, so what
is the rationale behind this decision?
AFAICS, the numeric for is simply a syntactical convenience which allows
loops like this:
i=1 repeat ... i = 1+3 until i>10
to be more cleanly coded as:
for i=1,10,3 do ... end
The generic for is quite different, syntactically and semantically. The
'=' changes to 'in' and the 'start,stop,step' list of (two or three)
numbers becomes an 'iterator,invariant,controlvar' list.
The similarity in syntax is convenient, familiar (other languages overload
'for' in an analogous way), and avoids the need for an additional keyword.
Despite the overloading of "for", the two sorts of looping constructs are
sufficiently differentiated, at least in my mind, by the use of "=" and
"in".
I'm not sure why you'd want or need to implement a numeric for using a
generic for (as you seem to want to do), though you can if you wish (just
not in the way you propose).
If the numeric for were implemented with the keyword "loop" instead of
"for," would that help to distinguish them? (If so, just read "for =" as
"loop" and "for in" as "for," and, lo, the issue vanishes :-)
Note (Blue PiL pp.32-33) the additional and not unimportant semantic
distinction that in the numeric for, the start,stop,step values must
evaluate to numbers and are evaluated just once, before the loop starts.
In generic for, the iterator function is called each time round the loop
until it returns nil.