Loops, break, continue and switch statements

WME script currently supports two types of loops: for loops and while loops.

for loops

The for statement specifies a counter variable, a test condition, and an action that updates the counter. Before each iteration of the loop, the condition is tested. If the test is successful, the code inside the loop is executed. If the test is unsuccessful, the code inside the loop is not executed, and the program continues on the first line of code immediately following the loop. After the loop is executed, the counter variable is updated before the next iteration begins.

 

A typical example, loop from 0 to 9:

 

for(var i=0; i<10; i=i+1)
{
  // ... some code here
}

Note: WME currently does not support the “++” and “--“ operators.

 

while loops

A while loop is similar to a for loop. The difference is, a while loop does not have a built-in counter variable or update expression. The code inside loop is repeatedly executed as long as the specified condition is true.

Example:

var MyVar = 5;
while(MyVar > 0)
{
  MyVar = MyVar - 1;
}

 

The break and continue statements

The break statement is used to stop the execution of a loop.
The continue statement can be used to jump immediately to the next iteration, skipping the rest of the code block

Example:

actor.GoToAsync(100, 200);
while(true) // an infinite loop
{
  if(actor.Ready) break; // leave the while loop if the actor finished the walking
  Sleep(20); // otherwise return the control to the engine and continue with the loop
}

 

The switch statement

The switch statement enables the execution of one or more statements when a specified expression's value matches a label.

switch (expression)
{

   case label :
       statementlist
   case label :
       statementlist
   ...
   default :
       statementlist
}

The "expression" is the expression to be evaluated, while "labels" are identifiers to be matched against the expression. When one of the labels matches the expressions, the statements following the label are executed until a break statement or end of the switch statement are encountered.

Use the default clause to provide a statement to be executed if none of the label values matches expression. The default branch must be the last in the list.

Example:

switch (Color)
{
  case "black":
    actor.Talk("Creepy");
  break;

  case "red":
    actor.Talk("Cheerful");
  break;

  case "yellow":
    actor.Talk("Bright");
  break;

  default:
    actor.Talk("Neutral");
}