Control Structures: Difference between revisions

From Bohemia Interactive Community
Jump to navigation Jump to search
(Simplify endless loop)
m (Minor reformatting)
(26 intermediate revisions by 17 users not shown)
Line 1: Line 1:
'''Control Structures''' are special [[Statement|statements]]. They are sequences of scripting code which help to control complex procedures. You can use control structures to define code which is only executed under certain conditions or repeated for a couple of times.
{{SideTOC}}
'''Control Structures''' are [[Statement|statements]] which are used to control execution flow in the scripts. They are sequences of scripting code which help to control complex procedures. You can use control structures to define code which is only executed under certain conditions or repeated for a couple of times.
 
''Note for advanced readers: in OFP/ArmA/VBS scripting language control structures are normal scripting commands, with no special handling compared to other commands. This is different from most imperative programming languages (like C), where control statements are implemented in the core language grammar. The "controlling" done by them is implemented by accepting [[Code|code]] as an argument. The complex control structures like "[[while]] ... [[do]] ..." are implemented using helper types, like [[While Type]].''
 


== Requirements ==
== Requirements ==
Line 13: Line 17:
'''Conditional structures''' help to define code which is only executed under certain circumstances. Often you will write code that depends on the game state, on other code or other conditions.
'''Conditional structures''' help to define code which is only executed under certain circumstances. Often you will write code that depends on the game state, on other code or other conditions.


=== <tt>if</tt>-Statement ===
=== <tt>[[if]]</tt>-Statement ===


The <tt>if</tt>-statement defines code that is only executed '''if''' a certain condition is met. The syntax of it looks like that:
The <tt>if</tt>-statement defines code that is only executed '''if''' a certain condition is met. The syntax of it looks like that:


  if (CONDITION) then
  [[if]] (CONDITION) [[then]]
  {
  {
     STATEMENT;
     STATEMENT;
Line 30: Line 34:
  [[if]] (_temperature < 0) [[then]]
  [[if]] (_temperature < 0) [[then]]
  {
  {
     [[hint]] "Snow!"
     [[hint]] "Snow!";
  };
  };


Line 36: Line 40:
In this example, first the value of <tt>_temperature</tt> is checked:
In this example, first the value of <tt>_temperature</tt> is checked:


* If the value is greater than 0, the nested code is ignored.
* If the value is 0 or greater than 0, the nested code is ignored.
* If the value is 0 or less than 0, the command <tt>hint "Snow!";</tt> is executed.
* If the value is less than 0, the command <tt>hint "Snow!";</tt> is executed.


==== Alternative Code ====
==== Alternative Code ([[else]]) ====


You can also define ''alternative'' code that is executed, when the condition is ''not'' <tt>true</tt>.
You can also define ''alternative'' code that is executed, when the condition is ''not'' <tt>true</tt>.


  if (CONDITION) then
  [[if]] (CONDITION) [[then]]
  {
  {
     STATEMENT;
     STATEMENT1;
     ...
     ...
  }
  }
  else
  [[else]]
  {
  {
     STATEMENT;
     STATEMENT2;
     ...
     ...
  };
  };


Another way of specifying an alternative code is done by feeding a 2-dimensional [[Array]] of [[Code]] into the [[then]] like this (but this alternative is CPU-heavier):
[[if]] (CONDITION) [[then]] [{STATEMENT1; ...}, {STATEMENT2; ...}];
In fact the above syntax with the Array is the only possible syntax as [[else]] does nothing else than taking the code to it's left and the one to it's right and packs them both into a 2-dimensional [[Array]] of [[Code]] which is then fed into the [[then]] operator. But using [[else]] is just as fine and in most cases better in case of readability of your code.<br>
Here you have a second sequence of [[Statement|statements]] executed when <tt>CONDITION</tt> is <tt>false</tt>.
Here you have a second sequence of [[Statement|statements]] executed when <tt>CONDITION</tt> is <tt>false</tt>.


==== More than one statement (SQS syntax - deprecated) ====
==== Conditional assignments ====
If...then structures can also be used to assign conditional values to variables:
<code>_living = [[if]] (alive player) [[then]] { true } [[else]] { false };</code>
 
 
==== SQS syntax (deprecated) ====


A good way in [[SQS syntax]] is the use of labels ([[goto]]) when you need to execute more than one statement within [[if]]-code or [[else]]-code.
Within [[SQS syntax]] the use of [[goto]] labels is a way to execute more than one statement within if...then structures.


  [[if]] (CONDITION) [[then]] {[[goto]] "label"}
  [[if]] (CONDITION) [[then]] { [[goto]] "label" }
  ... some other statements
  ... some other statements
  #label
  #label
Line 70: Line 84:
'''Example 1: (without [[else]])'''
'''Example 1: (without [[else]])'''


  [[if]] (_temperature < 0) [[then]] {[[goto]] "Snow"}
  [[if]] (_temperature < 0) [[then]] { [[goto]] "Snow" }
  ... some other statements
  ... some other statements
  #Snow
  #Snow
   [[hint]] "Snow!"
   hint "Snow!"
   [[echo]] "There is snow!"
   echo "There is snow!"
   variable = [[text]] "Hey. Snow outside."
   variable = text "Hey. Snow outside."




'''Example 2: (with [[else]])'''
'''Example 2: (with [[else]])'''


  [[if]] (_temperature < 0) [[then]] {[[goto]] "Snow"} [[else]] {[[goto]] "Sunshine"}
  [[if]] (_temperature < 0) [[then]] { [[goto]] "Snow" } [[else]] { [[goto]] "Sunshine" }
  ... some other statements
  ... some other statements
  Goto "Continue"
  Goto "Continue"
Line 87: Line 101:
   [[echo]] "There is snow!"
   [[echo]] "There is snow!"
   variable = [[text]] "Hey. Snow outside."
   variable = [[text]] "Hey. Snow outside."
   Goto "Continue"
   [[goto]] "Continue"
  #Sunshine
  #Sunshine
   [[hint]] "No Snow but sunshine!"
   [[hint]] "No Snow but sunshine!"
   [[echo]] "There is no snow!"
   [[echo]] "There is no snow!"
   variable = [[text]] "Hey. No snow outside."
   variable = [[text]] "Hey. No snow outside."
   Goto "Continue"
   [[goto]] "Continue"
  #Continue
  #Continue
   ...
   ...


==== Nested <tt>if</tt>-Statements ====
==== Nested <tt>[[if]]</tt>-Statements ====


Since the <tt>if</tt>-statement is itself a [[Statement|statement]], you can also create '''nested <tt>if</tt>-statements'''.
Since the <tt>if</tt>-statement is itself a [[Statement|statement]], you can also create '''nested <tt>if</tt>-statements'''.
Line 102: Line 118:
'''Example:'''
'''Example:'''


  if ([[alive]] [[player]]) then
  [[if]] (alive player) then
  {
  {
     if ([[someAmmo]] [[player]]) then
     [[if]] (someAmmo player) then
     {
     {
         [[hint]] "The player is alive and has ammo!";
         hint "The player is alive and has ammo!";
     }
     }
     else
     [[else]]
     {
     {
         [[hint]] "The player is out of ammo!";
         hint "The player is out of ammo!";
     }
     };
  }
  }
  else
  [[else]]
  {
  {
     [[hint]] "The player is dead!";
     hint "The player is dead!";
  };
  };


=== <tt>switch</tt>-Statement ===
=== <tt>[[switch]]</tt>-Statement ===


([[Armed Assault]] only)
(Starting from [[{{arma}}]])


In some cases you may want to check a [[Variables|variable]] for several values and execute different code depending on the value. With the above knowledge you could just write a sequence of <tt>if</tt>-statements.
In some cases you may want to check a [[Variables|variable]] for several values and execute different code depending on the value.
With the above knowledge you could just write a sequence of <tt>if</tt>-statements.


  if (_color == "blue") then
  [[if]] (_color == "blue") [[then]]
  {
  {
     hint "What a nice color";
     hint "What a nice color";
  }
  }
  else
  [[else]]
  {
  {
     if (_color == "red") then
     [[if]] (_color == "red") [[then]]
     {
     {
         hint "Don't you get aggressive?";
         hint "Don't you get aggressive?";
Line 140: Line 157:
The <tt>switch</tt>-statement compares a variable against different values:
The <tt>switch</tt>-statement compares a variable against different values:


  switch (VARIABLE) do
  [[switch]] (VARIABLE) [[do]]
  {
  {
     case VALUE1:
     [[case]] VALUE1:
     {
     {
         STATEMENT;
         STATEMENT;
Line 148: Line 165:
     };
     };
   
   
     case VALUE2:
     [[case]] VALUE2:
     {
     {
         STATEMENT;
         STATEMENT;
Line 161: Line 178:
'''Example:'''
'''Example:'''


  switch (_color) do
  [[switch]] (_color) do
  {
  {
     case "blue":
     [[case]] "blue":
     {
     {
         hint "What a nice color";
         hint "What a nice color";
     };
     };
   
   
     case "red":
     [[case]] "red":
     {
     {
         hint "Don't you get aggressive?";
         hint "Don't you get aggressive?";
Line 174: Line 191:
  };
  };


==== <tt>default</tt>-Block ====
==== <tt>[[default]]</tt>-Block ====


In some cases you may want to define alternative code that is executed, when none of the values matches. You can write this code in a <tt>default</tt>-Block.
In some cases you may want to define alternative code that is executed, when none of the values matches. You can write this code in a <tt>default</tt>-Block.
{{ Important | Note that there is '''no colon''' (<tt>:</tt>) after the <tt>default</tt> tag! }}


  switch (VARIABLE) do
  [[switch]] (VARIABLE) [[do]]
  {
  {
     case VALUE1:
     [[case]] VALUE1:
     {
     {
         STATEMENT;
         STATEMENT;
Line 186: Line 204:
     };
     };
   
   
     case VALUE2:
     [[case]] VALUE2:
     {
     {
         STATEMENT;
         STATEMENT;
Line 194: Line 212:
     ...
     ...
   
   
     default
     [[default]]
     {
     {
         STATEMENT;
         STATEMENT;
Line 200: Line 218:
     };
     };
  };
  };
==== variable assignments ====
Switch can be used to assign different values to a variable:
<code>_color = [[switch]] (side player) [[do]] { [[case]] west: {"ColorGreen"}; [[case]] east: {"ColorRed"}; };</code>


== Loops ==
== Loops ==
'''Loops''' are used to execute the same [[Block|code block]] for a specific or unspecific number of times.
'''Loops''' are used to execute the same [[Block|code block]] for a specific or unspecific number of times.


=== <tt>while</tt>-Loop ===
=== <tt>[[while]]</tt>-Loop ===
This loop repeats the same code block as long as a given [[Boolean]] [[condition]] is <tt>true</tt>.
This loop repeats the same code block as long as a given [[boolean]] condition is <tt>true</tt>.
 
<tt>While</tt> loops are limited to 10,000 cycles. After that the loop is exited, no matter what the looping condition. A workaround to this limitation is to use a [[Control_Structures#Endless for-do Loop|non-incrementing for...do loop]].


  while {CONDITION} do
  [[while]] {CONDITION} [[do]]
  {
  {
     STATEMENT;
     STATEMENT;
Line 221: Line 241:


If <tt>CONDITION</tt> is <tt>false</tt> from the beginning on, the statements within the block of the loop will never be executed.
If <tt>CONDITION</tt> is <tt>false</tt> from the beginning on, the statements within the block of the loop will never be executed.
Because the test of the while expression takes place before each execution of the loop, a while loop executes zero or more times.


'''Example:'''
'''Example:'''
Line 226: Line 248:
  _counter = 0;
  _counter = 0;
   
   
  while {_counter < 10} do
  [[while]] {_counter < 10} [[do]]
  {
  {
     _counter = _counter + 1;
     _counter = _counter + 1;
  };
  };


=== <tt>for</tt>-Loop ===
=== <tt>[[for]]</tt>-Loop ===


([[Armed Assault]] only)
(Starting from [[{{arma}}]])


The <tt>for</tt>-loop repeats the same code block for a specific number of times.
The <tt>for</tt>-loop repeats the same code block for a specific number of times.


  for [{BEGIN}, {CONDITION}, {STEP}] do
  [[for]] [{BEGIN}, {CONDITION}, {STEP}] [[do]]
  {
  {
     STATEMENT;
     STATEMENT;
Line 259: Line 281:


  // a loop repeating 10 times
  // a loop repeating 10 times
  for [{_i=0}, {_i<10}, {_i=_i+1}] do
  [[for]] [{_i = 0}, {_i < 10}, {_i = _i + 1}] [[do]]
  {
  {
     [[player]] [[globalChat]] _i;
     player globalChat format ["%1", _i];
  };
  };


Line 284: Line 306:
# The variable <tt>_i</tt> is incremented by 1, back to step 2.
# The variable <tt>_i</tt> is incremented by 1, back to step 2.


==== <tt>for</tt>-<tt>from</tt>-<tt>to</tt>-Loop ====
==== <tt>[[for]]</tt>-<tt>[[from]]</tt>-<tt>[[to]]</tt>-Loop ====


There exists an alternate syntax of the <tt>for</tt>-loop, which simplifies the last example a bit.
There exists an alternate syntax of the <tt>for</tt>-loop, which simplifies the last example a bit.


  for "VARNAME" from STARTVALUE to ENDVALUE do
  [[for]] "VARNAME" [[from]] STARTVALUE [[to]] ENDVALUE [[do]]
  {
  {
     STATEMENT;
     STATEMENT;
Line 296: Line 318:
* <tt>VARNAME</tt> is any name given to the variable used to count the loop
* <tt>VARNAME</tt> is any name given to the variable used to count the loop
* <tt>STARTVALUE</tt> is a [[Number]] value given to the counter variable before the loop starts
* <tt>STARTVALUE</tt> is a [[Number]] value given to the counter variable before the loop starts
* <tt>ENDVALUE</tt> is a [[Number]] value until which the counter is incremented/decremented
* <tt>ENDVALUE</tt> is a [[Number]] value until which the counter is incremented
{{Important| Note: Unless using a custom [[step]] as seen below, ENDVALUE must be greater than STARTVALUE for the loop to execute}}


The loop processes as follows:
The loop processes as follows:


#A variable with the name <tt>VARNAME</tt> is initialized with <tt>STARTVALUE</tt>
#A variable with the name <tt>VARNAME</tt> is initialized with <tt>STARTVALUE</tt>
#If <tt>VARNAME</tt> is not equal to <tt>ENDVALUE</tt>, the code block is executed
#If <tt>VARNAME</tt> does not exceed <tt>ENDVALUE</tt>, the code block will be executed.
#
#The variable <tt>VARNAME</tt> is incremented by 1
##If <tt>ENDVALUE</tt> is greater than <tt>STARTVALUE</tt>, the variable <tt>VARNAME</tt> is incremented by 1
##If <tt>ENDVALUE</tt> is less than <tt>STARTVALUE</tt>, the variable <tt>VARNAME</tt> is decremented by 1
#Go back to step 2
#Go back to step 2


Line 312: Line 333:


  // a loop repeating 10 times
  // a loop repeating 10 times
  for "_i" from 0 to 9 do
  [[for]] "_i" [[from]] 0 [[to]] 9 [[do]]
  {
  {
     [[player]] [[globalChat]] _i;
     player globalChat format ["%1", _i];
  };
  };


Line 324: Line 345:
#Back to step 2
#Back to step 2


==== <tt>for</tt>-<tt>from</tt>-<tt>to</tt>-Loop with custom <tt>step</tt> ====
==== <tt>[[for]]</tt>-<tt>[[from]]</tt>-<tt>[[to]]</tt>-Loop with custom <tt>[[step]]</tt> ====


The default step to increment the variable in <tt>for</tt>-<tt>from</tt>-<tt>to</tt>-Loops is 1. You can set a custom step though using this syntax:
The default step to increment the variable in <tt>for</tt>-<tt>from</tt>-<tt>to</tt>-Loops is 1. You can set a custom step though using this syntax:


  for "VARNAME" from STARTVALUE to ENDVALUE step STEP do
  [[for]] "VARNAME" [[from]] STARTVALUE [[to]] ENDVALUE [[step]] STEP [[do]]
  {
  {
     STATEMENT;
     STATEMENT;
Line 335: Line 356:


* <tt>STEP</tt> is a [[Number]] which defines the step by which the variable is incremented every loop
* <tt>STEP</tt> is a [[Number]] which defines the step by which the variable is incremented every loop
{{Important| Note: Utilizing this method, you can perform loops where VARNAME decrements by using a negative [[step]] value combined with a STARTVALUE that is greater than ENDVALUE}}


The rest is equal to the above section.
The rest is equal to the above section.
Line 341: Line 363:


  // a loop repeating 5 times
  // a loop repeating 5 times
  for "_i" from 0 to 9 step 2 do
  [[for]] "_i" [[from]] 0 [[to]] 9 [[step]] 2 [[do]]
  {
  {
     [[player]] [[globalChat]] _i;
     player globalChat format ["%1", _i];
  };
  };


Line 353: Line 375:
#Back to step 2
#Back to step 2


<div id="endless_for">
=== <tt>[[forEach]]</tt>-Loop ===
==== Endless <tt>for-do</tt> Loop ====
To overcome the limitation of 10,000 cycles within <tt>while</tt> loops, you can use a non-incrementing <tt>for...do</tt> loop like this:
for [{}, {true}, {true}] do
{
    sleep 0.001;
    STATEMENT;
    if (your_exit_condition) then {_loop=1;};
};
 
=== <tt>forEach</tt>-Loop ===


You will often use the <tt>for</tt>-loop to increment over [[Array|arrays]].
You will often use the <tt>for</tt>-loop to increment over [[Array|arrays]].
Line 369: Line 381:
  _array = [unit1, unit2, unit3];
  _array = [unit1, unit2, unit3];
   
   
  for [{_i=0}, {_i < count _array}, {_i=_i+1}] do
  [[for]] [{_i = 0}, {_i < count _array}, {_i = _i+1}] [[do]]
  {
  {
     (_array select _i) setDamage 1;
     (_array select _i) setDamage 1;
Line 380: Line 392:
     ...
     ...
  }
  }
  forEach ARRAY;
  [[forEach]] ARRAY;


The code block is executed exactly <tt>([[count]] ARRAY)</tt> times.
The code block is executed exactly <tt>([[count]] ARRAY)</tt> times.


You may use the [[Magic Variables|magic variable]] <tt>_x</tt> within the code block, which always references to the current item of the array.
You may use the [[Magic Variables|magic variable]] <tt>_x</tt> within the code block, which always references to the current item of the array.
Magic variable <tt>_foreachindex</tt> contains current index of the _x element in ARRAY.


'''Example:'''
'''Example:'''
Line 393: Line 406:
     _x setDamage 1;
     _x setDamage 1;
  }
  }
  forEach _array;
  [[forEach]] _array;


'''Description:'''
'''Description:'''
Line 400: Line 413:
# In the second loop, the statement <tt>unit2 setDamage 1;</tt> is executed
# In the second loop, the statement <tt>unit2 setDamage 1;</tt> is executed
# In the third loop, the statement <tt>unit3 setDamage 1;</tt> is executed
# In the third loop, the statement <tt>unit3 setDamage 1;</tt> is executed
'''NOTE: Each iteration (also when it consists of plural commands) will be executed within one frame, so be aware of large and/or complex code blocks!'''


== Return Values ==
== Return Values ==


Control structures always return the '''last [[expression]] evaluated''' within the structure. Note that there '''must not''' be a semicolon (;) after this value, otherwise [[Nothing]] is returned.
Control structures always return the '''last [[expression]] evaluated''' within the structure.


'''Correct example:'''
'''Example:'''
 
if (myCondition) then {myValueA} else {myValueB};
=> returns myValueA or myValueB


'''Incorrect example:'''
  [[if]] (myCondition) [[then { myValueA; } else { myValueB; };
 
  if (myCondition) then {myValueA;} else {myValueB;};
   
   
  => returns [[Nothing]]
  returns myValueA or myValueB


== See also ==
== See also ==
Line 421: Line 430:
* [[Statement]]
* [[Statement]]
* [[Expression]]
* [[Expression]]


[[Category: Syntax]]
[[Category: Syntax]]
[[Category: Scripting Topics]]
[[Category:ArmA: Control Structures]]

Revision as of 15:37, 9 July 2019

Template:SideTOC Control Structures are statements which are used to control execution flow in the scripts. They are sequences of scripting code which help to control complex procedures. You can use control structures to define code which is only executed under certain conditions or repeated for a couple of times.

Note for advanced readers: in OFP/ArmA/VBS scripting language control structures are normal scripting commands, with no special handling compared to other commands. This is different from most imperative programming languages (like C), where control statements are implemented in the core language grammar. The "controlling" done by them is implemented by accepting code as an argument. The complex control structures like "while ... do ..." are implemented using helper types, like While Type.


Requirements

To fully understand this article you should read the following articles:

Conditional Structures

Conditional structures help to define code which is only executed under certain circumstances. Often you will write code that depends on the game state, on other code or other conditions.

if-Statement

The if-statement defines code that is only executed if a certain condition is met. The syntax of it looks like that:

if (CONDITION) then
{
    STATEMENT;
    ...
};
  • CONDITION is a Boolean statement or variable which returns either true or false. The code nested in the following block is only executed if the condition is true, else ignored.
  • STATEMENT is a custom sequence of statements. That may be commands, assignments, control structures etc.

Example:

if (_temperature < 0) then
{
    hint "Snow!";
};


In this example, first the value of _temperature is checked:

  • If the value is 0 or greater than 0, the nested code is ignored.
  • If the value is less than 0, the command hint "Snow!"; is executed.

Alternative Code (else)

You can also define alternative code that is executed, when the condition is not true.

if (CONDITION) then
{
    STATEMENT1;
    ...
}
else
{
    STATEMENT2;
    ...
};

Another way of specifying an alternative code is done by feeding a 2-dimensional Array of Code into the then like this (but this alternative is CPU-heavier):

if (CONDITION) then [{STATEMENT1; ...}, {STATEMENT2; ...}];

In fact the above syntax with the Array is the only possible syntax as else does nothing else than taking the code to it's left and the one to it's right and packs them both into a 2-dimensional Array of Code which is then fed into the then operator. But using else is just as fine and in most cases better in case of readability of your code.
Here you have a second sequence of statements executed when CONDITION is false.

Conditional assignments

If...then structures can also be used to assign conditional values to variables: _living = if (alive player) then { true } else { false };


SQS syntax (deprecated)

Within SQS syntax the use of goto labels is a way to execute more than one statement within if...then structures.

if (CONDITION) then { goto "label" }
... some other statements
#label
  statement1
  statement2
  statement3


Example 1: (without else)

if (_temperature < 0) then { goto "Snow" }
... some other statements
#Snow
  hint "Snow!"
  echo "There is snow!"
  variable = text "Hey. Snow outside."


Example 2: (with else)

if (_temperature < 0) then { goto "Snow" } else { goto "Sunshine" }
... some other statements
Goto "Continue"
#Snow
  hint "Snow!"
  echo "There is snow!"
  variable = text "Hey. Snow outside."
  goto "Continue"

#Sunshine
  hint "No Snow but sunshine!"
  echo "There is no snow!"
  variable = text "Hey. No snow outside."
  goto "Continue"

#Continue
 ...

Nested if-Statements

Since the if-statement is itself a statement, you can also create nested if-statements.

Example:

if (alive player) then
{
    if (someAmmo player) then
    {
        hint "The player is alive and has ammo!";
    }
    else
    {
        hint "The player is out of ammo!";
    };
}
else
{
    hint "The player is dead!";
};

switch-Statement

(Starting from Arma)

In some cases you may want to check a variable for several values and execute different code depending on the value. With the above knowledge you could just write a sequence of if-statements.

if (_color == "blue") then
{
    hint "What a nice color";
}
else
{
    if (_color == "red") then
    {
        hint "Don't you get aggressive?";
    }
};

The more values you want to compare, the longer gets this sequence. That is why the simplified switch-statement was introduced.

The switch-statement compares a variable against different values:

switch (VARIABLE) do
{
    case VALUE1:
    {
        STATEMENT;
        ...
    };

    case VALUE2:
    {
        STATEMENT;
        ...
    };

    ...
};

The structure compares VARIABLE against all given values (VALUE1, VALUE2, ...). If any of the values matches, the corresponding block of statements is executed.

Example:

switch (_color) do
{
    case "blue":
    {
        hint "What a nice color";
    };

    case "red":
    {
        hint "Don't you get aggressive?";
    };
};

default-Block

In some cases you may want to define alternative code that is executed, when none of the values matches. You can write this code in a default-Block.

Note that there is no colon (:) after the default tag!
switch (VARIABLE) do
{
    case VALUE1:
    {
        STATEMENT;
        ...
    };

    case VALUE2:
    {
        STATEMENT;
        ...
    };

    ...

    default
    {
        STATEMENT;
        ...
    };
};

variable assignments

Switch can be used to assign different values to a variable: _color = switch (side player) do { case west: {"ColorGreen"}; case east: {"ColorRed"}; };

Loops

Loops are used to execute the same code block for a specific or unspecific number of times.

while-Loop

This loop repeats the same code block as long as a given boolean condition is true.

while {CONDITION} do
{
    STATEMENT;
    ...
};

Note the curled braces for the condition. The loop processes as follow:

  1. CONDITION is evaluated. If it is true, go on to 2., else skip the block and go on with the code following the loop.
  2. Execution of all nested statements. Go back to 1.

If CONDITION is false from the beginning on, the statements within the block of the loop will never be executed.

Because the test of the while expression takes place before each execution of the loop, a while loop executes zero or more times.

Example:

_counter = 0;

while {_counter < 10} do
{
    _counter = _counter + 1;
};

for-Loop

(Starting from Arma)

The for-loop repeats the same code block for a specific number of times.

for [{BEGIN}, {CONDITION}, {STEP}] do
{
    STATEMENT;
    ...
};
  • BEGIN is a number of statements executed before the loop starts
  • CONDITION is a Boolean condition evaluated before each loop
  • STEP is a number of statements executed after each loop

The loop processes as follows:

  1. BEGIN is executed
  2. CONDITION is evaluated. If it is true, go on to 3., else skip the block and go on with the code following the loop.
  3. The statements in the code block are executed
  4. STEP is executed, go on to 2.

If CONDITION is false from the beginning on, the code block will never be executed.

Example:

// a loop repeating 10 times
for [{_i = 0}, {_i < 10}, {_i = _i + 1}] do
{
    player globalChat format ["%1", _i];
};

will display

0
1
2
3
4
5
6
7
8
9

Description:

  1. The variable _i is set to 0
  2. The condition _i<10 is evaluated, which is true until _i surpasses 9.
  3. The code player globalChat _i; is executed
  4. The variable _i is incremented by 1, back to step 2.

for-from-to-Loop

There exists an alternate syntax of the for-loop, which simplifies the last example a bit.

for "VARNAME" from STARTVALUE to ENDVALUE do
{
    STATEMENT;
    ...
};
  • VARNAME is any name given to the variable used to count the loop
  • STARTVALUE is a Number value given to the counter variable before the loop starts
  • ENDVALUE is a Number value until which the counter is incremented
Note: Unless using a custom step as seen below, ENDVALUE must be greater than STARTVALUE for the loop to execute

The loop processes as follows:

  1. A variable with the name VARNAME is initialized with STARTVALUE
  2. If VARNAME does not exceed ENDVALUE, the code block will be executed.
  3. The variable VARNAME is incremented by 1
  4. Go back to step 2

The following example is semantically equal to the last example.

Example:

// a loop repeating 10 times
for "_i" from 0 to 9 do
{
    player globalChat format ["%1", _i];
};

Description:

  1. _i is set to 0
  2. player globalChat 0 is executed
  3. _i is incremented by 1 => _i is now 1
  4. Back to step 2

for-from-to-Loop with custom step

The default step to increment the variable in for-from-to-Loops is 1. You can set a custom step though using this syntax:

for "VARNAME" from STARTVALUE to ENDVALUE step STEP do
{
    STATEMENT;
    ...
};
  • STEP is a Number which defines the step by which the variable is incremented every loop
Note: Utilizing this method, you can perform loops where VARNAME decrements by using a negative step value combined with a STARTVALUE that is greater than ENDVALUE

The rest is equal to the above section.

Example:

// a loop repeating 5 times
for "_i" from 0 to 9 step 2 do
{
    player globalChat format ["%1", _i];
};

Description:

  1. _i is set to 0
  2. player globalChat 0 is executed
  3. _i is incremented by 2 => _i is now 2
  4. Back to step 2

forEach-Loop

You will often use the for-loop to increment over arrays.

_array = [unit1, unit2, unit3];

for [{_i = 0}, {_i < count _array}, {_i = _i+1}] do
{
    (_array select _i) setDamage 1;
};

The forEach-loop does exactly that: It repeats the same code block for every item in an array.

{
    STATEMENT;
    ...
}
forEach ARRAY;

The code block is executed exactly (count ARRAY) times.

You may use the magic variable _x within the code block, which always references to the current item of the array. Magic variable _foreachindex contains current index of the _x element in ARRAY.

Example:

_array = [unit1, unit2, unit3];

{
    _x setDamage 1;
}
forEach _array;

Description:

  1. In the first loop, the statement unit1 setDamage 1; is executed
  2. In the second loop, the statement unit2 setDamage 1; is executed
  3. In the third loop, the statement unit3 setDamage 1; is executed

NOTE: Each iteration (also when it consists of plural commands) will be executed within one frame, so be aware of large and/or complex code blocks!

Return Values

Control structures always return the last expression evaluated within the structure.

Example:

if (myCondition) [[then { myValueA; } else { myValueB; };

→ returns myValueA or myValueB

See also