how the value of "number" was changed in a LUA iterator?

Viewed 30

I'm just a beginner of LUA. I don't understand why the value of the object "number" was changed in this body. Thanks in advance if you could answer me.

function square(iteratorMaxCount, number)--how the value of "number" was changed?
    currentNumber = number + 1
    if currentNumber<=iteratorMaxCount
    then
        return currentNumber, currentNumber*currentNumber, number
    end
end


for i,n ,k in square,3,-1
do
    print(i,n,k)
end

this is the solution:

lua.exe iterator.lua
0   0   -1
1   1   0
2   4   1
3   9   2

1 Answers

after the initial call of square in a for loop, number set to the value of currentNumber returned from the last call.

This is a "stateless" iterator, Programming in Lua: 7.3 – Stateless Iterators covers this topic.

The semantics of a for loop are discussed Programming in Lua: 7.2 – The Semantics of the Generic for

With the information from those section we can know, that a for loop works as described 7.2

    do
      local _f, _s, _var = explist
      while true do
        local var_1, ... , var_n = _f(_s, _var)
        _var = var_1
        if _var == nil then break end
        block
      end
    end

our function square would be the function referenced as _f. after each loop we pass in the first value returned by the square back into it as the second arg, shown above as _var.

Related