[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: What's the rationale behind "for i=a,b[,c]"?
- From: Sean Conner <sean@...>
- Date: Tue, 17 Mar 2015 12:57:35 -0400
It was thus said that the Great Choonster TheMage once stated:
> On 17 March 2015 at 21:45, Soni L. <fakedme@gmail.com> wrote:
> >
> > 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.
> >
> >
>
> What about this?
>
> local a,b,c = 1,10,nil
> for i = a, b, c or 1 do
> <mycode>
> end
Or ...
function range(low,high,delta)
local up = function(v) return v <= high end
local down = function(v) return v >= high end
local d
local cmp
if not delta then
if low < high then
d = 1
else
d = -1
end
else
d = delta
end
if d > 0 then
cmp = up
else
cmp = down
end
return function(s,v)
v = v + d
if cmp(v) then
return v
end
end,nil,low-d
end
for x in range(string.byte("AZ",1,2)) do
print(x)
end
for x in range(1,10,1) do print(x) end
for x in range(10,1,-1) do print(x) end
for x in range(string.byte("ZA",1,2),-1) do
print(x)
end
-spc (And just skip the whole "for i = low,high ..." thing entirely)
- References:
- What's the rationale behind "for i=a,b[,c]"?, Soni L.
- Re: What's the rationale behind "for i=a,b[,c]"?, Dirk Laurie
- Re: What's the rationale behind "for i=a,b[,c]"?, Soni L.
- Re: What's the rationale behind "for i=a,b[,c]"?, Choonster TheMage