For Loops

For loops have most complex syntax of the loops in Lua, but they're also usually the most commonly used.

For loops are, mainly, for running a block of code a set number of times, or for iterating through a table.

To the right, you'll see an example of the first type of for loop- one that runs a specific number of times. Let's examine each part of it.

For, do, end, and the comma are just for structure, they are required, but they can't be changed to affect the loop. However, the i = 1 and 10 parts are able to be changed and can affect the loop.

Here's how that works: i will start at 1, and be incremented by 1 until it reaches 10. You can replace the 1 to have a new starting value (you can even use a variable), and you can change the 10 to have a new ending value, this can also be a variable. Optionally, you can add another comma after the 10 and put in another number, which will be how much i is incremented by each cycle. Also of note, i is a variable. Specifically, it is a local variable to the for loop. Remember when those were mentioned back in the lesson on variables? Well, if you don't, here's a refresher: A local variable is only accessible within the statement it is declared in. In other words, for our friend i here, you can only use it within this for loop.

As you might guess, it can be useful to have access to the current value of i in a given iteration of the loop. But what about the other type of loop? The one that lets you iterate over a table's keys and values. Let's look at the next two examples.

Syntax is different this time. Now we have two local variables being declared in the loop, and an array or table being used in a function called ipairs or pairs. What's going on?

It's actually quite simple. This code causes the loop to look at a table, and, starting with its first entry, get its value. k is the key of the entry, and v is that entry's value. Then, on the next iteration of the loop, it looks at the next entry, rinse and repeat. As before, k and v can have different names. Now what's with ipairs and pairs? Well, those are the functions that iterate over the tables and get the keys and values. But why are there two? Also simple. ipairs is for arrays starting at 1, and pairs is for tables that have non-numerical keys. If you have a table that is just a list, it is considered best practice to use ipairs.

for i = 1, 10 do
--code here
end

for k, v in ipairs(array) do
--code here
end

for k, v in pairs(table) do
--code here
end