Range Iterator |
|
for i=i,j,k do end syntax. It can be used for example when the two or three parameters of the basic for loop are returned by another function. -- JeromeVuarand
function range(from, to, step) step = step or 1 return function(_, lastvalue) local nextvalue = lastvalue + step if step > 0 and nextvalue <= to or step < 0 and nextvalue >= to or step == 0 then return nextvalue end end, nil, from - step end
Example use:
function f() return 10, 0, -1 end for i in range(f()) do print(i) end
function range(from, to, step) step = step or 1 local f = step > 0 and function(_, lastvalue) local nextvalue = lastvalue + step if nextvalue <= to then return nextvalue end end or step < 0 and function(_, lastvalue) local nextvalue = lastvalue + step if nextvalue >= to then return nextvalue end end or function(_, lastvalue) return lastvalue end return f, nil, from - step end