Factory function unable to return the local iterator to for loop in lua? -
why can't factory function fromto
return local function iter
iterator loop?
function fromto(from,to) return iter,to,from-1 end local function iter(to,from)--parameter:invariant state, control variable = + 1 if <= return else return nil end end in fromto(1,10) print(i) end
as @yuhao says, scheme can work. there few ways rearrange code. here's one:
local function fromto(from,to) --parameter:invariant state, control variable local function iter(to,from) = + 1 if <= return else return nil end end return iter,to,from-1 end in fromto(1,10) print(i) end
two things understand: variable scope , functions values.
variables either global or local. local variables lexically scoped. in scope statement following declaration end of block. if name not name of local variable becomes global variable reference. on line 2,
iter
global variable.functions not declared, values created when function definition expression executed. (a function defintion statement alternate syntax function definition expression , assignment variable.) also, functions don't have names. referenced 1 or more variables. so, function value exist , referenced
iter
variable until execution control passes through lines contain function definition. in code, that's end of line 11.
Comments
Post a Comment