For Loop on Lua
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.
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