T
The 5.2 version manual has a Portuguese version, https://www.lua.org/manual/5.2/pt/manual.html#3.3.5 :The command for generic works using functions, calls iterators. To each iteration, the iterator function is called to produce a new value, stopping when this new value is -. The loop for Generic has the following syntax:command : for list names in listexps the Block endList names ::= Name {‘,’ Name!A command for asfor var1, ..., varn in listaexps do bloco end
is equivalent to the code:do
local f, s, var = listaexps
while true do
local var1, ..., varn = f(s, var)
if var1 == nil then break end
var = var1
bloco
end
end
Note the following:listexps is evaluated only once. Your results are a function iterator, one State, and an initial value for the first variable.f, s, and rod are invisible variables. The names are here for didactic purposes only.You can use break break to get out of a loop for.
The loop variables vari are local to the loop; you cannot use their value after for finish. If you need these values, then assign them to other variables before interrupting or exiting the loop.So, commenting:The expression between in and the No for generic is an ordered triple; the first element is a function, the second is an auxiliary value, and the third is the iteration index.When iterating, the function that is the first element of the triple will be called with the other two elements as parameters. The second element is constant throughout the loop, and often is the collection being iterated. The third is the current element or index, and will be used by the function to decide which is the next element to return.For example, we will examine an iterator as pairs(table): If you run on https://www.lua.org/cgi-bin/demo :> print(pairs(io))
you will get back something like this:function: 0x41b980 table: 0x22d2ca0 nil
That is, a function, a table, and a nil. Making:> local f, t, n = pairs(io)
> print((f == next), (t == io), n)
true true nil
you find that the function pairs() returned is the next() and the object is the table itself io that she received as a parameter. Saying:> next(io, nil)
write function: 0x41de30
> next(io, 'write')
nil
you go through the table elements io (which only contains one item in that environment, called write). This execution of the next() is how to turn the loop "in the hand"; what for does is simply pass the results of next to the body of the loop in the order in which it receives them.