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 the for loop. The for loop declares a local variable, also called so-called names ; the fact that a variable was previously defined using names is completely irrelevant. Any use of names inside a for loop will refer to local, not global.
The for loop states that the inside of the loop will be called using 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 internal code once for each value that it counts.
What you really 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 elements of the Lua table. Lua tables map keys to values. Your array automatically creates integer keys that increase. Thus, the key associated with "Joe" in the table is 2 (Lua indexes always begin with 1).
Therefore, you need a for loop that calculates from 1 to 3, which you get. You use the count variable to access an element from the table.
However, this has a drawback. What happens if you remove one of the items from the list?
names = {'John', 'Joe'} for nameCount = 1, 3 do print (names[nameCount]) end
Now we get John Joe nil , as trying to access values ββfrom a table that does not exist results in nil . To avoid this, we need to count from 1 to the length of the table:
names = {'John', 'Joe'} for nameCount = 1,
# is the length operator. It works with tables and rows, returning the length. Now, no matter how big or small names , this will always work.
However, there is a more convenient way to iterate over an array of elements:
names = {'John', 'Joe', 'Steve'} for i, name in ipairs(names) do print (name) end
ipairs is a standard Lua function that iterates through a list. This style of the for loop, an iterator for a loop, uses such an iterator function. The value i is the index of the record in the array. The value of name is the value of this index. So it basically does a lot of work for you.