User Tools

Site Tools


hpl2:amnesia:script_language_reference_and_guide:control_flow_-_loops

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
hpl2:amnesia:script_language_reference_and_guide:control_flow_-_loops [2013/01/08 02:19]
thegreatcthulhu Found a replacement for the weird TDD code snippet (written by someone inexperienced?)
hpl2:amnesia:script_language_reference_and_guide:control_flow_-_loops [2015/06/16 10:24]
romulator [Discussion] Changed "peaces" to "pieces".
Line 37: Line 37:
 ===== Discussion ===== ===== Discussion =====
  
-Loops are a powerful tool; they allow you to execute ​peaces ​of code several times in a row, to iterate over array elements, to easily assign the same callback to several game objects using just one line of code, and more. This is achieved by providing a //​condition//​ which the loop uses to determine how many times, or for how long, it should repeat the execution of it's body (the part between ''​{''​ and ''​}''​). A loop cycle is also called an //​iteration//​.+Loops are a powerful tool; they allow you to execute ​pieces ​of code several times in a row, to iterate over array elements, to easily assign the same callback to several game objects using just one line of code, and more. This is achieved by providing a //​condition//​ which the loop uses to determine how many times, or for how long, it should repeat the execution of it's body (the part between ''​{''​ and ''​}''​). A loop cycle is also called an //​iteration//​.
  
 ==== The While-Loop ==== ==== The While-Loop ====
Line 126: Line 126:
   - The //step// expression is executed. The execution jumps back to (2.)   - The //step// expression is executed. The execution jumps back to (2.)
   - The execution continues on the first line of code after the loop.   - The execution continues on the first line of code after the loop.
 +
 +A simple example to begin with:
 +<code c++>
 +int sum = 0;
 +
 +for(int i = 0; i < 3; ++i) 
 +{
 +    sum = sum + 5;
 +}
 +</​code>​
 +
 +The loop above iterates 3 times (since the counter ''​i''​ takes values 0, 1, and 2). The code has the exact same effect as if this was written instead:
 +<code c++>
 +int sum = 0;
 +
 +sum = sum + 5;     // sum =  0 + 5 =  5
 +sum = sum + 5;     // sum =  5 + 5 = 10
 +sum = sum + 5;     // sum = 10 + 5 = 15
 +</​code>​
  
  
Line 138: Line 157:
 } }
 </​code>​ </​code>​
 +
  
 What if you wanted to sum up only the even integers in the 1--10 range? Well, here's one way to do it: What if you wanted to sum up only the even integers in the 1--10 range? Well, here's one way to do it:
hpl2/amnesia/script_language_reference_and_guide/control_flow_-_loops.txt ยท Last modified: 2015/06/16 10:24 by romulator