[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: What's the rationale behind "for i=a,b[,c]"?
- From: Dirk Laurie <dirk.laurie@...>
- Date: Tue, 17 Mar 2015 06:24:42 +0200
2015-03-17 2:14 GMT+02:00 Soni L. <email@example.com>:
> What's the rationale behind being able to do "for i=1,10" but not "for
> i=string.byte("AZ",1,2)"? (i.e. why are commas syntactically significant in
> this case, but not in "for x,y in next, t"?)
> (Ofc, if we had a range() instead of numeric for, we would be able to do
> "for i in range(string.byte("AZ",1,2))", and then this question would make
> no sense, but we don't. So, what's the rationale?)
Look at the syntax definitions. Generic for has:
for namelist in explist do block end
Name lists and expression lists are expected. No commas are required.
If the last expression in an expression list is a function call, then all the
return values enter the list. Hence the possibility of functions like pairs().
All that is prescribed is for the first expression in the list to be a function.
But arithmetic for has:
for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end
Twi or three comma-separated expressions are required, not an explist.
It may look like an explist but it isn't. The expressions are evaluated one
by one at compile time, tested for being numbers and assigned to the
loop control variables. Only the first value is kept if `exp` is something
with multiple values.
> function demo(...)
>> for i = ... , ... , ... do print(i) end