lua-users home
lua-l archive

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




On 17/03/15 01:24 AM, Dirk Laurie wrote:
2015-03-17 2:14 GMT+02:00 Soni L. <fakedme@gmail.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
end
demo(1,10,2)
1

local a,b,c = 1,10,nil
for i=a,b,c do print(i) end -- doesn't work because of the explicit nil :/ why's nil not a valid "no value" here? :/

So there's no easy way to do it, other than:

local a,b,c = 1,10,nil
if c == nil then
  for i=a,b do
    <mycode>
  end
else
  for i=a,b,c do
    <mycode> -- we have to duplicate the code?!
  end
end

Which's bad due to duplicated code

--
Disclaimer: these emails are public and can be accessed from <TODO: get a non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.