Control Structures#
In sclang
, control sequences are functions.
They expect one or multiple functions that are executed conditionally.
Use Cases#
We already saw the if
-function, which expect one boolean expression (a predicate) and two functions.
x = 5;
if(x >= 5, {"x >= 5".postln;}, {"x < 5".postln;});
The first function is evaluated if the statement is true, otherwise the second function is evaluated.
Another way to branch the code execution is achieved by using the switch
-statement.
It expects one value
which is then compared to one or more testvalues
and each of these is paired with a function that will be executed if value == testvalue
.
x = 5;
(
switch(x, // value
3, {"x == 3".postln;}, // testvalue and testfunction pairs
4, {"x == 4".postln;},
5, {"x == 5".postln;},
6, {"x == 6".postln;},
{"x is something else".postln;} // default function
);
)
A kind of the if
- and switch
-statement is the case
-statement.
The case method allows for conditional evaluations with multiple cases (similar to the switch) but instead of a test value, we have a test function.
(
var i, x, z;
z = [0, 1, 1.1, 1.3, 1.5, 2];
i = z.choose;
x = case
{ i == 1 } { \no }
{ i == 1.1 } { \wrong }
{ i == 1.3 } { \wrong }
{ i == 1.5 } { \wrong }
{ i == 2 } { \wrong }
{ i == 0 } { \true };
x.postln;
)
Iteration#
The while
-function expects one predicate and another function that can be executed as long as the predicate is true.
For example:
(
var i = 0;
while({i < 10}, {i.postln; i = i + 1;});
)
The for
-function works much more restricted:
(
for(0, 9, {arg i; i.postln;})
)
A little more flexible is the forBy
-function for which for
is a special case.
It allows us to define an additional stepValue
:
(
forBy(0, 9, 2, {arg i; i.postln;}) // 0 2 4 6 8
)
The do
-function iterates over a given sequence, similar to a foreach
of other languages (for
in Python
).
(
do((1..9), {arg item, i; item.post; ",".post; i.postln;})
)
Here item
is the element of the Array
generated by (1..9)
and i
is the index of the element!
A switch
-function expects a value
and pairs of tested values and functions to be executed.
The test checks for equality ==
.
To be more flexible and to use different predicates one can use the case
-function which is as efficient as if
-statements.