For Loop on Lua

195,076

Solution 1

Your problem is simple:

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end

This code first declares a global variable called names. Then, you start a for loop. The for loop declares a local variable that just happens to be called names too; the fact that a variable had previously been defined with names is entirely irrelevant. Any use of names inside the for loop will refer to the local one, not the global one.

The for loop says that the inner part of the loop will be called with names = 1, then names = 2, and finally names = 3. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.

What you actually wanted was something like this:

names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).

Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.

However, this has a flaw. What happens if you remove one of the elements from the list?

names = {'John', 'Joe'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

Now, we get John Joe nil, because attempting to access values from a table that don't exist results in nil. To prevent this, we need to count from 1 to the length of the table:

names = {'John', 'Joe'}
for nameCount = 1, #names do
  print (names[nameCount])
end

The # is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names gets, this will always work.

However, there is a more convenient way to iterate through an array of items:

names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
  print (name)
end

ipairs is a Lua standard function that iterates over a list. This style of for loop, the iterator for loop, uses this kind of iterator function. The i value is the index of the entry in the array. The name value is the value at that index. So it basically does a lot of grunt work for you.

Solution 2

By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:

Way1

names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end

Way2

names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end

Way1 uses the table index/key , on your table names each element has a key starting from 1, for example:

names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John

So you just make i go from 1 to 3.

On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:

names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end

prints the following:

1   John
2   Joe
myKey   myValue
Share:
195,076
SamYoungNY
Author by

SamYoungNY

Updated on November 28, 2020

Comments

  • SamYoungNY
    SamYoungNY over 3 years

    My assignment is how to do a for loop. I have figured it out in terms of numbers but cannot figure it out in terms of names. I would like to create a for loop that runs down a list of names. Following is what I have so far:

    names = {'John', 'Joe', 'Steve'}
    for names = 1, 3 do
      print (names)
    end
    

    I have tried some other things but it just doesn't work, the terminal always just lists 1, 2, 3... What I am doing wrong?

  • Nicol Bolas
    Nicol Bolas over 12 years
    You read the tables tutorial, but you didn't see ipairs? Or the part where pairs doesn't have to return the key values in any particular order?
  • derp
    derp over 12 years
    I actually used ipairs at first but when I added the myKey="myValue" example that needs pairs for the non-numeric key I decided to change the rest for pairs as well. I'm sorry if I omitted that the order is not guaranteed with pairs but I left the link right there for him to read.
  • boctulus
    boctulus about 8 years
    So, for with ipairs() works as foreach() in other languages
  • Fraser
    Fraser almost 8 years
    Great answer, I would just add that in the final example it is fairly customary to use _ when the var is unused. e.g. names = {'John', 'Joe', 'Steve'} for _, name in ipairs(names) do print (name) end
  • Dejavu
    Dejavu about 7 years
    Downvoter: please provide a valid reason for downvoting. Even though I think the answer is misleading in that names (the integer counter) as declared in the for scope introduces a local variable, which shadows the names (the table array) as declared in the global scope.