Functions

A function in sclang is an expression which defines operations to be performed when it is sent the value message. It has no name or identifier attached to it, which is known as lambda expression or anonymous function in other programming languages. Function definitions in sclang are enclosed in curly brackets {}, f.e.:

{ 3 + 4 }

Functions are not evaluated immediately when they occur in code, but their definitions are passed as values just like integers or strings.

f = { 3 + 4 };  // Let f be this function - no evaluation yet.
f.value;        // Perform the operation, see Post window for output.

Arguments

Argument declarations, if any, follow the open bracket.

f = { arg a, b;  a*a + b}  // Let f be a function that takes two arguments
f.value(2, 3)              // Pass the arguments in order and evaluate it
f.value(b: 3, a: 2)        // Arguments can be passed by name, in any order
f.value(2)                 // Oops, second argument is nil.

Default values for the arguments can be provided in the following form:

{ arg a = 1, b = 2;  a*a + b}

Controlling arguments

Arguments in sclang are more than they seem to be. You have control over the arguments outside the function. This is very useful in the context of sound production.

f = { arg f = 440, m = 0.1; SinOsc.ar(freq: f, mul: m)!2 }
p = f.play;

// Change the value of the arguments while the Synth is playing
p.set(\f, 350);
p.set(\m, 0.3);

First class citizens

Functions are themselves ─ so called ─ first class citizens in the language and can are treated like other simple types. For example, you can return a function from a function.

~makeF = { arg v; { arg a; v*a } }
t = ~makeF.value(3)
t.value(2)

They can also be passed as arguments. For example, arrays provide the method collect that expects a function as argument.

[0, 1, 2, 3, 4].collect({ arg i; i*i + 1 })

To be continued.

  • Scope
  • Variables
  • Syntax variations
  • Methods

See http://doc.sccode.org/Reference/Functions.html for more information.