Control structures in SuperCollider are implemented via message sends. Here are a few of those available. See Syntax Shortcuts for the various ways expressions can be written.
Conditional execution is implemented via the if
message. The if
message is sent to an expression which must return a Boolean value.
In addition it takes two arguments: a function to execute if the expression is true and another optional function to execute if the expression is false. The if
message returns the value of the function which is executed. If the falseFunc is not present and the expression is false then the result of the if message is nil.
Syntax
if(expr) { true body } { false body };
// alternate
if(expr, trueFunc, falseFunc);
// possible but harder to read, so, not preferred
expr.if (trueFunc, falseFunc);
Examples
xxxxxxxxxx
if([false, true].choose) {
"expression was true".postln // true function
} {
"expression was false".postln // false function
};
)
(
var a = 1, z;
z = if(a < 5) { 100 } { 200 };
z.postln;
)
(
var x;
if(x.isNil) { x = 99 };
x.postln;
)
The while message implements conditional execution of a loop. If the testFunc answers true when evaluated, then the loopFunc is evaluated and the process is repeated. Once the testFunc returns false, the loop terminates.
Syntax
xxxxxxxxxx
while { testFunc body } { loopFunc body };
// alternate
while({ testFunc body }, { loopFunc body });
// possible but harder to read, so, not preferred
{ testFunc body }.while({ loopFunc body });
Example
xxxxxxxxxx
(
i = 0;
while { i < 5 } { i = i + 1; "boing".postln };
)
while expressions are also optimized by the compiler if they do not contain variable declarations in the testFunc and the loopFunc.
The for message implements iteration over an integer series from a starting value to an end value stepping by one each time. A function is evaluated each iteration and is passed the iterated numeric value as an argument.
Syntax
xxxxxxxxxx
for(startValue, endValue) { loop body }
// alternate
for(startValue, endValue, function)
// possible but harder to read, so, not preferred
startValue.for ( endValue, function )
Example
xxxxxxxxxx
for(3, 7) { arg i; i.postln }; // prints values 3 through 7
The forBy selector implements iteration over an integer series with a variable step size. A function is evaluated each iteration and is passed the iterated numeric value as an argument.
Syntax
xxxxxxxxxx
forBy(startValue, endValue, stepValue) { loop body };
forBy(startValue, endValue, stepValue, function);
// possible but harder to read, so, not preferred
startValue.forBy(endValue, stepValue, function);
Example
xxxxxxxxxx
forBy(0, 8, 2) { arg i; i.postln }; // prints values 0 through 8 by 2's
Do is used to iterate over a Collection. Positive Integers also respond to do
by iterating from zero up to their value. Collections iterate, calling the function for each object they contain. Other kinds of Objects respond to do by passing themselves to the function one time. The function is called with two arguments, the item, and an iteration counter.
Syntax
xxxxxxxxxx
collection.do { loop body };
// alternate
collection.do(function)
// alternates, rarely seen
do(collection, function)
do(collection) { loop body };
Example
xxxxxxxxxx
[ 1, 2, "abc", (3@4) ].do { arg item, i; [i, item].postln; };
5.do { arg item; item.postln }; // iterates from zero to four
"you".do { arg item; item.postln }; // a String is a collection of characters
'they'.do { arg item; item.postln }; // a Symbol is a singular item
(8..20).do { arg item; item.postln }; // iterates from eight to twenty
(8,10..20).do { arg item; item.postln }; // iterates from eight to twenty, with stepsize two
Routine {
var i = 10;
while { i > 0 } {
i.yield;
i = i - 5.0.rand
}
}.do { arg item; item.postln }; // 'do' applies to the Routine
(8..20).do
uses an optimization to avoid generating an array that is used only for iteration (but which would be discarded thereafter). The return value of (8..20).do { |item| item.postln }
is 8, the starting value.
However, if do
is written as an infix binary operator, as in (8..20) do: { |item| item.postln }
, then it will generate the series as an array first, before calling Array:do. One side effect of this is that it is valid to do
over an infinite series within a routine only if do
is written as a method call. If it is written as a binary operator, you will get a "wrong type" error because the array must be finite.
xxxxxxxxxx
// OK: 'do' is a method call
r = Routine {
(8 .. ).do { |i|
i.yield;
};
};
r.next;
-> 8
-> 9 etc.
// ERROR: 'do' is an operator
r = Routine {
(8 .. ) do: { |i|
i.yield;
};
};
r.next;
ERROR: Primitive '_SimpleNumberSeries' failed.
Wrong type.
Object implements a switch method which allows for conditional evaluation with multiple cases. These are implemented as pairs of test objects (tested using if this == test.value) and corresponding functions to be evaluated if true.
The switch statement will be inlined if the test objects are all Floats, Integers, Symbols, Chars, nil, false, true and if the functions have no variable or argument declarations. The inlined switch uses a hash lookup (which is faster than nested if statements), so it should be very fast and scale to any number of clauses.
switch
construction that is not inlined will test ==
, while one that is inlined will test ===
. See the examples. One implication is that strings should be avoided: switch(text) { "abc" } { ... }
may not match, even if text == "abc"
. Symbols are preferred.(2/3) == (1 - (1/3))
is false. Therefore floats should be avoided in switch
constructions.Syntax
xxxxxxxxxx
switch(value)
{ testvalue1 } { truebody1 }
{ testvalue2 } { truebody2 }
{ testvalue3 } { truebody3 }
{ testvalue4 } { truebody4 }
...
{ defaultbody };
switch(value,
testvalue1, trueFunction1,
testvalue2, trueFunction2,
...
testvalueN, trueFunctionN,
defaultFunction
);
Examples
xxxxxxxxxx
(
var x = 0; //also try 1
switch(x, 0, { "hello" }, 1, { "goodbye" })
)
(
var x = 0; //also try 1
switch(x) { 0 } { "hello" } { 1 } { "goodbye" };
)
(
var x, z;
z = [0, 1, 1.1, 1.3, 1.5, 2];
switch (z.choose.postln,
1, { \no },
1.1, { \wrong },
1.3, { \wrong },
1.5, { \wrong },
2, { \wrong },
0, { \true }
).postln;
)
or:
xxxxxxxxxx
(
var x, z;
z = [0, 1, 1.1, 1.3, 1.5, 2];
x = switch(z.choose)
{1} { \no }
{1.1} { \wrong }
{1.3} { \wrong }
{1.5} { \wrong }
{2} { \wrong }
{0} { \true };
x.postln;
)
Inlined vs non-inlined comparison:
xxxxxxxxxx
(
switch(1.0)
{ 1 } { "yes" }
{ "no" }
)
-> no
The identity comparison 1.0 === 1
is false: while 1.0 and 1 represent the same numeric value, one is floating point and the other is an integer, so they cannot be identical.
xxxxxxxxxx
(
// 'var x' prevents inlining
switch(1.0)
{ 1 } { var x; "yes" }
{ "no" }
)
WARNING: Float:switch is unsafe, rounding via Float:asInteger:switch
-> yes
Function implements a case method which allows for conditional evaluation with multiple cases. Since the receiver represents the first case this can be simply written as pairs of test functions and corresponding functions to be evaluated if true. Case is inlined and is therefore just as efficient as nested if statements.
Example
xxxxxxxxxx
(
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;
)
Function implements a try
method which allows catching exceptions thrown by code and run the exception handler. For more information see Exception.
Example
xxxxxxxxxx
try {
...code...
} { |error|
...exception handler...
};
Function implements a protect
method which allows protecting code from exceptions thrown by code. The difference with try
is the exception handler code is always run, even if there is no exception. If an exception occurs, it is rethrown after the exception handler block is run. For more information see Exception.
Example
xxxxxxxxxx
file = File(path, "r");
protect {
// work with the file here, which might cause an error
} {
file.close;
};
Using Functions, many control structures can be defined like the ones above. In the class Collection: Iteration there are many more messages defined for iterating over Collections.
if
, while
, switch
and case
expressions are optimized (i.e. inlined) by the compiler if they do not contain variable declarations in the functions. The optimization plucks the code from the functions and uses a more efficient jump statement:
xxxxxxxxxx
(
{
if(6 == 9) {
"hello".postln;
} {
"world".postln;
}
}.def.dumpByteCodes
)
BYTECODES: (20)
0 2C 06 PushInt 6
2 2C 09 PushInt 9
4 E6 SendSpecialBinaryArithMsg '=='
5 F8 00 07 JumpIfFalse 7 (15)
8 41 PushLiteral "hello"
9 B0 TailCallReturnFromFunction
10 C1 3A SendSpecialMsg 'postln'
12 FC 00 04 JumpFwd 4 (19)
15 40 PushLiteral "world"
16 B0 TailCallReturnFromFunction
17 C1 3A SendSpecialMsg 'postln'
19 F2 BlockReturn
-> < closed FunctionDef >
Failure to inline due to variable declarations:
xxxxxxxxxx
(
{
if(6 == 9, {
var notHere;
"hello".postln;
},{
"world".postln;
})
}.def.dumpByteCodes
)
WARNING: FunctionDef contains variable declarations and so will not be inlined.
in file 'selected text'
line 4 char 14:
var notHere;
"hello".postln;
-----------------------------------
BYTECODES: (13)
0 2C 06 PushInt 6
2 2C 09 PushInt 9
4 E6 SendSpecialBinaryArithMsg '=='
5 04 00 PushLiteralX instance of FunctionDef - closed
7 04 01 PushLiteralX instance of FunctionDef - closed
9 B0 TailCallReturnFromFunction
10 C3 0B SendSpecialMsg 'if'
12 F2 BlockReturn
-> < closed FunctionDef >
You can switch on and off the above warning (see: LanguageConfig: *postInlineWarnings)
xxxxxxxxxx
LanguageConfig.postInlineWarnings_(true) // warn
LanguageConfig.postInlineWarnings_(false) // ignore it.