Can anyone explain to me what is a generic Moon tie?

I already know the ties while,repeat and for, but when I was looking at the types of loops, in the section I found the SUCH of the" generic for Loop". The text was in English.

Author: arthurgps2, 2017-04-19

1 answers

The manual of version 5.2 has a Portuguese version, whose relevant part I quote below :

The generic for command works using functions, called iterators. With each iteration, the iterator function is called to produce a new value, stopping when that new value is nil. The generic for loop has the following syntax:

Command:: = for listanomes in listaexps do Block end

Listanames:: = Name {‘,’ 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:

  • listexps is evaluated only once. Its results are an iterator function , a state, and an initial value for the first iterator variable .
  • f , s , and var are invisible variables. The names are here for educational purposes only.
  • you can use break to break out of a loop for. Loop variables vari are local to the loop; you cannot use their value after for ends. If you need these values, then assign them to other variables before interrupting or exiting the loop.

Then commenting:

The expression between the in and the of the in the generic for is an ordered triple; the first element is a function, the second is an auxiliary value, and the third is the index of the iteration.

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, let's look at an iterator like pairs(table): If you run on REPL of demonstration of lua.org :

> print(pairs(io))

You will get back something like the following:

function: 0x41b980  table: 0x22d2ca0    nil

I.e. a function, a table, and a nil. Doing:

> local f, t, n = pairs(io)
> print((f == next), (t == io), n)
true    true    nil

You find that the function that pairs() returned is next() and the object is the table itself io that it received as parameter. Saying:

> next(io, nil)
write   function: 0x41de30
> next(io, 'write')
nil

You scroll through the elements of the table io (which only contains one item in that environment, called write). This execution of next() is like turning the loop "in 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.

 1
Author: Wtrmute, 2017-04-19 18:00:58