lua-users home
lua-l archive

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


Hello,

This is a variant of "abolishing the numeric-for" -- and keep ipairs()! This proposal is inspired by Python, which often does the right choice, I guess.
The point is that the numeric-for can be considered as a special case of generic traversal loops. So, we may have a builtin Interval (*) factory function to traverse an interval; not necessary, but to avoid users reinventing the wheel. Then, using the generic for:

   for i in Interval(start,stop,step) do ... end

I find this pattern elegant and I guess it makes numeric-for superfluous.
Below an example Interval factory in Lua. Actually, we may have a look at the current implementation of the numeric-for, to do the right thing and exactly reproduce the semantics.


Interval = function(start, stop, step)
    if not start then
        error "Interval requires a start bound."
    end
    if not stop then
        error "Interval requires a stop bound."
    end
    if not step then step = 1 end
    if step == 0 then
        error "U, joker! Zero is not a valid Interval step ;-)"
    end
    n = start
    if step < 0 then
        return function()
            if n < stop then return nil end
            result = n
            n = n + step
            return result
        end
    else
        return function()
            if n > stop then return nil end
            result = n
            n = n + step
            return result
        end
    end
end

require "io"    ; write = io.write
for n in Interval(1,9) do write(n,' ') end ; print()
for n in Interval(9,1) do write(n,' ') end ; print()
for n in Interval(1,9,3) do write(n,' ') end ; print()
for n in Interval(9,1,-2) do write(n,' ') end ; print()
for n in Interval(1.3,3.9,0.333) do write(n,' ') end ; print()
-- *** errors ***
--for n in Interval(1) do write(n,' ') end
--for n in Interval() do write(n,' ') end
--for n in Interval(1,9,0) do write(n,' ') end


Denis

(*) I chose "Interval", partly for a change, partly because it's an international word.
________________________________

vit esse estrany ☣

spir.wikidot.com