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?
Your problem is simple:
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 callednamestoo; the fact that a variable had previously been defined withnamesis entirely irrelevant. Any use ofnamesinside 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, thennames = 2, and finallynames = 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:
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?
Now, we get
John Joe nil, because attempting to access values from a table that don’t exist results innil. To prevent this, we need to count from 1 to the length of the table:The
#is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or smallnamesgets, this will always work.However, there is a more convenient way to iterate through an array of items:
ipairsis a Lua standard function that iterates over a list. This style offorloop, the iterator for loop, uses this kind of iterator function. Theivalue is the index of the entry in the array. Thenamevalue is the value at that index. So it basically does a lot of grunt work for you.