OK, the first variant is the "simple" one, in terms of technology, maybe not in terms of understanding it.
really means "do something a number of times" (which is what iteration means).
So
is the same as
Code: Select all
print "hi"
print "hi"
print "hi"
print "hi"
The big difference is that with iteration, you're in charge how often the code gets repeated, it could be something else every single time.
Even more interesting is when you do "break" on a certain condition. "break" is a way to sort of bail out of the loop. "Okay, I said I was going to run this bit a hundred times, but after ten times, I realised I was already done, so you can skip on the ninety iterations to come."
And "i" (or whatever you call it) is the counter, that keeps track of where you are.
"while" and the other forms of iteration are mostly the same.
If you still don't get numerical for, say so and we'll go a bit more in depth.
Now, the second form of for:
This is a bit of a higher level thing, and you can think of it like a "for each": "for each something in iterator do code"
Example:
"For each enemy in this level, update it."
Now tables in Lua are very simple and they are not what is called iterators.* So, in come the functions pairs and ipairs, which take a table and return an iterator.
Doing
Code: Select all
for index, item in ipairs(list) do
print(index, item)
end
is equivalent to doing
Code: Select all
for index = 1, #list do -- you know the length operator?
local item = list[index]
print(index, item)
end
That means giving the above
Code: Select all
list = {}
list[1] = 4
list[2] = 6
list.hi = 2
list[100] = 8
will print
Now pairs on the other hand iterates over
all keys. That means it can't deliver them in order, but whatever. Doing a
Code: Select all
for key, item in pairs(list) do
print(key, item)
end
will probably print something like
I hope this helps a bit.
* In languages like Python, this is different, you can do:
Code: Select all
friends = ["Ellie", "Morgan", "Chuck", "Devon"]
for person in friends:
print person, "is my friend"