For Loops

Explanation of For Loops.

by moosethepooh

Author Avatar

Explantation

For loops have 4 main parts: The count variable. The start. The end. The increment.

The count variable is personal prefrence. The start is where the loop will begin, and it will run until it reaches the end. The increment is how the loop will count up. If it's positive it will go up, and if it's negative it'll go down. The default increment is 1.

Example

for i = 1, 10 do
    print(i);
end

Output:

1 2 3 4 5 6 7 8 9 10

"i" is the count variable, 1 is the start, and 10 is the end. As you see, the loop goes until it reaches 10. Now watch what happens when I add an increment.

Example

for i = 0, 10, 2 do
    print(i);
end

Output:

0 2 4 6 8 10

The loop goes up by 2 this time. You can also go down.

for i = 10,  1, -1 do
    print(i);
end

Output:

10 9 8 7 6 5 4 3 2 1

You can also use for loops with tables. Which is a little different. Let's set up an array and dictionary with some string values.

local fruitArray = {"apples", "bananas", "grapes"};

local vegtableColorDictionary = {
    Lettuce = "Green";
    Eggplant = "Purple";
    Carrot = "Orange";
}

With this type of for loops there are 4 parts. The index or key, the variable, pairs() or iparirs(), and the table. When working with an array you use index and ipairs(). When working with a dictionary you use key and pairs(). Let's use a for loop with our fruit array first.

Example

for i, v in ipairs(fruitArray) do
    print(i..":"..v);
end

Output:

1:apples 2:bananas 3:grapes

The "i" stands for what position(index) in the array the variable is. The "v" stands for the variable. You can use the same logic with a dictionary, just instead of the index, it'd be the key.

for k, v in pairs(vegtableColorDictionary) do
    print(k..":"..v);
end

Output:

Carrot:Orange Eggplant:Purple Lettuce:Green

The order flips in a dictionary.

Wrapping up

For loops are very useful in scripting. You can use them to make countdowns and many many more things. Using them with tables helps is also great.