Why can't the factory function fromto
return the local function iter
as an iterator to the for loop?
function fromto(from,to)
return iter,to,from-1
end
local function iter(to,from)--parameter:invariant state, control variable
from = from + 1
if from <= to then
return from
else
return nil
end
end
for i in fromto(1,10) do
print(i)
end
As @YuHao says, your scheme can work. There are a few ways you could rearrange your code. Here's one:
local function fromto(from,to)
--parameter:invariant state, control variable
local function iter(to,from)
from = from + 1
if from <= to then
return from
else
return nil
end
end
return iter,to,from-1
end
for i in fromto(1,10) do
print(i)
end
Two things to understand: variable scope and functions are values.
Variables are either global or local. Local variables are lexically scoped. They are in scope from the statement following their declaration up to the end of the block. If a name is not the name of a local variable it becomes a global variable reference. On your line 2, iter
is a global variable.
Functions are not declared, they are values created when a function definition expression is executed. (A function defintion statement is simply an alternate syntax for a function definition expression and assignment to a variable.) Also, functions don't have names. They are simply referenced by one or more variables. So, your function value does exist and get referenced by the iter
variable until execution control passes through the lines that contain the function definition. In your code, that's the end of line 11.