generic for statement

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

generic for statement

fschmidt
Administrator
The Lua generic for statement takes 3 arguments to support alternatives to closures for iterators.  This includes stateless iterators and passing a state variable to the function.  I don't see the point of these options which just add complexity to the language.  In all cases, using a closure is the simplest and cleanest solution.  So I think the generic for statement should only take one argument which should be a closure.
Woe to those who call bad good and good bad -- Isaiah 5:20
Following the Old Testament, not evil modern culture
Reply | Threaded
Open this post in threaded view
|

Re: generic for statement

Hugo <Nabble>
This should be fine. So, just to confirm, a loop like this would work:
t = {10, 20, 30}
for element in values(t) do
    print(element)
end
But values() would NOT be implemented like this:
function values(t)
    next, t, nil
end
But rather it could be implemented with closures:
function values(t)
    local pos = 0
    return function()
        i = i + 1
        return t[i]
    end
end
Correct? If yes, I agree. In the worst case we would be able to add the three-variables concept later and still keep compatibility with any previous code, right?
Reply | Threaded
Open this post in threaded view
|

Re: generic for statement

fschmidt
Administrator
Yes to all your questions.  This is how it is now implemented, so closing thread.
Woe to those who call bad good and good bad -- Isaiah 5:20
Following the Old Testament, not evil modern culture