1
I already know the bonds while
,repeat
and for
,but when I was seeing the types of loops, for
generic" . The text was in English.
1
I already know the bonds while
,repeat
and for
,but when I was seeing the types of loops, for
generic" . The text was in English.
1
Version 5.2 manual has a Portuguese version, whose relevant part I quote below:
The command for generic works using functions, calls of iterators. At each iteration, the iterator function is called to produce a new value, stopping when this new value is nil. The noose for generic has the following syntax:
commando ::= for list names in lists of block end
list names ::= Name {EVER,' Name}
A command for as
for 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:
- lists is evaluated only once. Your results are a function iterator, one state, and an initial value for the first iterator variable.
- f, s, and var are invisible variables. Names are here for educational purposes only.
- You can use break to get out of a loop for. The loop variables Vari are locations to the loop; you cannot use their value after the for end. If you need these values, then assign them to other variables before interrupting or exiting the loop.
So commenting:
The expression between the in and the of in the 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 frequently is the collection that is 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, let’s look at an iterator like pairs(table)
: If you run on REPL demonstration of the moon.org:
> print(pairs(io))
you will get back something like the following:
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 discover that the function that pairs()
returned is the next()
and the object is the table itself io
which she received as a parameter. Saying:
> next(io, nil)
write function: 0x41de30
> next(io, 'write')
nil
you scroll through the table elements io
(which contains only one item in that environment, called write
). Such execution of next()
is like turning the loop "in the hand"; what the for is simply to pass on the results of next
to the body of the loop in the order in which it receives them.
Browser other questions tagged loop lua for generic
You are not signed in. Login or sign up in order to post.
Do you know another language? You know how it is
foreach
?– Maniero