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?
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
Try:
names = {'John','Joe','Steve'}
for i = 1,3 do
print(names[i])
end
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
Source: Stackoverflow.com