Search code examples
for-looplua

For loops LUA Different Types


I wanted to learn more about for loops, as far as I know there are different types?

For instance,

for i = 1, 5 do
    print("hello")
end

^ I know about this one, it's going to print hello 5 times, but there are others like the one below which I do not understand, specifically the index bit (does that mean it is number 1?) and what is the ipairs for

for index, 5 in ipairs(x) do
    print("hello")
end

If there are any other types please let me know, I want to learn all of them and if you can provide any further reading I'd be more than greatful to check them out


Solution

  • As you can read in the Lua reference manual 3.3.5 For Statement

    The for statement has two forms: one numerical and one generic.

    The numerical for loop repeats a block of code while a control variable runs through an arithmetic progression. It has the following syntax:

    stat ::= for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end

    Example:

    for i = 1, 3 do
      print(i)
    end
    

    Will output

    1    
    2    
    3
    

    You seem familiar with that one. Read the reference manual section for more details.

    The generic for statement works over functions, called iterators. On each iteration, the iterator function is called to produce a new value, stopping when this new value is nil. The generic for loop has the following syntax:

    stat ::= for namelist in explist do block end namelist ::= Name {‘,’ Name}

    Example:

    local myTable = {"a", "b", "c"}
    for i, v in ipairs(myTable) do
      print(i, v)
    end
    

    Will ouput

    1  a
    2  b
    3  c
    

    ipairs is one of those iterator functions mentioned:

    Returns three values (an iterator function, the table t, and 0) so that the construction

    for i,v in ipairs(t) do body end will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value.

    Read more about ipairs and pairs here:

    https://www.lua.org/manual/5.3/manual.html#pdf-pairs

    https://www.lua.org/manual/5.3/manual.html#pdf-ipairs

    Of course you can implement your own iterator functions!

    Make sure you also read:

    Programming in Lua: 7 Iterators and the Generic for