Loop

From Mario Fan Games Galaxy Wiki
 Stub.png This article or section is in need of expansion.

Please add further information.

A loop is a statement or function that repeatedly executes a block of code. Loops execute until a condition has been met, for example, a window being closed. Almost every language provides basic forms of loops. There are several kinds of loops.

Types of Loops

While and Do-While

While loops are one of the most common forms of loop, and in most cases, a while loop can be used to replicate other kinds of loops. A while loop will run until a set condition is met. For example:

while (window_open())
{
  draw_window();
}

This code would run draw_window() until the window_open() function returns a false boolean value.

Oftentimes, while loops are used for "indefinite" loops, where it is unknown how many times that they will be run.

In addition to the standard while loop, there is also a do-while loop, which requires code to be executed at least once. For example:

do
{
  draw_window();
}
while (window_open())

Would run draw_window() at least once even if window_open() never returns true.

For

For loops offer a more advanced while which is used for "definite" loops. These loops are often used when an amount of code is intended to be run a set number of times. For example:

for (i = 0; i < 5; i++)
{
  display(i);
}

This code would run the code display(i) five times. Its output would be similar to:

0
1
2
3
4

For loops actually just provide a shorthand notation for while loops. The code given above is identical to:

i = 0;
while (i < 5)
{
  display(i);
  i++;
}

Foreach

Foreach loops provide a shorthand notation for for loops. For example, take this code:

i = {1, 2, 3, 4, 5};
foreach (i : j)
{
  display(j);
}

This code would be equivalent to:

i = {1, 2, 3, 4, 5};
for (j = 0; j < i.size(); j++)
{
  display(i[j]);
}

Repeat

Repeat statements offer shorthand for for loops. The repeat loop will run a set number of times. For example:

repeat (5)
{
  do_something();
}

is equivalent to:

for (i = 0; i < 5; i++)
{
  do_something();
}

Examples of Loops

Lua

for i = 1, 10 do print(i) end -- for
for i, v in ipairs {'a', 'b', 'c', 'd', 'e'} do print(i, v) end -- foreach

local i = 0
while i < 10 do print(i) i = i + 1 end -- while

local i = 0
repeat print(i) i = i + 1 until i == 10 -- repeat-until