lua-users home
lua-l archive

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


Hi all,
      I don't understand the different between stateless iterator and stateful iterator?  

       I know the iterator factory function return 3 values, the iter function, the invariant state, the initial value for control variable. Does the stateless iterator means that the iter function only use the invariant state and initial value for control variable to calculate the next value ? there is not any other local variable in iterator factory function (which will be the variables in closures ?

       for the exercise 7.1 in Programming in Lua, does the follow code is correct answer ?

--stateful
--[[
function fromto(n,m)
local r = m - n
return function(min, i)
if i < r then
return min + i
else
return nil
end
end,n,0
end
--]]

--stateless
local function iter(m,n)
if n + 1 < m then 
return n + 1
else 
return nil 
end
end

function fromto(n,m)
return iter, m , n-1
end




for i in fromto(1,10) do
print(i)
end


Thanks.