Control structures

Control structures in SubScript are similar to those used in ordinary Scala code. Branching and several kinds of loops are available.

Branching

SubScript has an if ternary operator. Here is its syntax:

if (condition) then positiveBranch else negativeBranch

or:

if (condition) then positiveBranch

positiveBranch operand will be executed if condition is true, otherwise an optional negativeBranch will be executed. For example:

script live = var x = true ; if (x) then {println("Hello")} else {println("World")}

While loop

while is an unary operator, its operand is a boolean condition. while(condition) construct is used as an operand to a sequential operator, turning it into a loop. For example:

  script live = [
    var x = 0;
    while(x < 10) {x += 1} {println(x)}
  ]

In the last line the sequential operator is turned into a loop because of while. Note that the order of the operands doesn’t matter: the following code does the same thing:

  script live = [
    var x = 0;
    {x += 1} {println(x)} while(x < 10)
  ]

… operand

The ... is an operand that turns its sequential code operator into a loop. It can be treated as while(true). For example, the following code will output the numbers with an interval of one second:

  script live = (
    var x = 0;
    {x += 1} {println(x)} {* Thread sleep 1000 *} ...
  )

As in case of while, this operand can be used at any position with same effect, so, for example, the following code does the same job:

  script live = [
    var x = 0;
    {x += 1} {println(x)} ... {* Thread sleep 1000 *}
  ]

The ... operand is useful to specify event loops of various applications.

Leave a Reply