====== Loop ======
^ Loop ^^
^ Type | Guide |
^ Category | AYA/YAYA |
===== Introduction =====
Loops are a bit of code that is running and restarts from the beginning while a condition is true. They are useful with arrays and allow to check them entirely without knowing what size they have.
Even if the number of time the bit of code is needed is known, loops keep from rewritting the same bit of code if it must be running many times.
===== While loops =====
They are the more simple-looking loops but the most dangerous too.
Their structure are 'while ' and would run while the is true.
For example :
i = 0
while i < 10
{
i = i + 1
}
Here, we initialize a variable i at 0 and while i is smaller than 10, we add 1 to i. When i is equal (or superior) to 10, the loops will stop. The condition is 'i < 10'.
More precisely, we starts to initialize i to 0. Then we checks that i < 10 and if yes, 'i = i + 1' is ran. After that we check again if i < 10 and if yes, run again 'i = i + 1' and that while i < 10. At the end of this, i would be equal to 10.
The problem of this loops comes from the condition. If the condition never become false, the loops wouldn't end. For example 'while 1'. The condition never become false so the loops wouldn't end and run infinitely causing what we usually call a crash.
===== For loops =====
They are less dangerous than while loops.
Their structure is the more complex, it's 'for ; ; '
So for the previous example, we just add a little line otherwise it would be empty :
for i = 0 ; i < 10 ; i = i + 1
{
"A value of i during a loop : %(i)\n"
}
So here the initial situation would be 'i = 0', that's the first thing that would run before the loop in itself. At each loop, "A value of i during a loop : %(i)" would be ran and 'i = i + 1' would be done and the loops would run until i is equal or superior to 10. When we put a line of dialogue in loops, only one randomly would be displayed as all the lines of dialogues coming from the loops were next the one to an other despite all the -- that could be inside.
There are few chance of making infinite loops with for loops since the ending condition and what change from one loop to an other are at the same place.
===== Foreach loops =====
They are the more useful for manipulating arrays. In fact, they work only for lists or arrays. Their structure is 'foreach ; '
Here is an example :
array = IARRAY
array[0] = 1
array[1] = 2
array[2] = 3
i = 0
foreach array ; element
{
i = i + element
}
"i value : %(i)"
Here the code would be ran for each element in the array. So when the code starts, an array called 'array' would be created with three elements : 1, 2 and 3. The variable 'element' would take the value of the first element of the array, so 1. Then it would be added to i and 'element' would become the next element of the array, 2. The loops would end when the array ends and the value of i would be 6.
{{tag>AYA Guide YAYA}}