Product SiteDocumentation Site

11.3.2.4. Function Arguments

The most useful aspect of Functions is that they can produce varying results, depending on their input. For whatever reason, the input accepted by a Function is called an "argument." SuperCollider's Functions can accept any number of arguments - zero, one, or many. Argument values (called "parameters") are provided to a Function by adding them in parentheses after the name of the Function, separated with commas, like this: exampleFunction( 5, 7, 9 ); Argument variables are declared as the first statement in a Function, like this: arg oneNumber, twoNumber;
This program is significantly more complicated than previous examples, but it shows how useful Functions can be. Notice how the braces in that example are on different lines than the rest of the Function, which gives us more space within the Function to complete some useful work.
(
   var greeter =
   {
      arg name;
      ( "Hello" + name ).postln;
   };

   greeter.value( "Samantha" );
   greeter.value( "Jermain" );
   nil;
)
Here is how the program works:
  1. A variable named greeter is declared, and assigned a Function.
  2. The Function contains an argument called name, and outputs "Hello" plus the name given to it.
  3. The parentheses here ( "Hello" + name ) ensure that the two strings are added together before the postln message prints them out.
  4. The greeter variable is used to call the Function with two different names.
  5. The nil; statement is optional, and does not affect the operation of the program. What it does is return a "nothing" value to the interpreter after program execution completes, so that the last message is not repeated.
Since every argument has a name, SuperCollider allows you to use that name when executing the function. This example executes the greeter function from the last example:
greeter.value( name:"Myung-Whun" );
This is more useful if there are many arguments, and you do not remember the order that they appear in the Function's definition.
SuperCollider also allows you to specify default values for arguments, so that they do not need to be specified. This allows optional customization of a Function's behaviour, and is therefore very powerful.
This example modifies the one above by adding default-value arguments, and by calling arguments with their name. As you can see, I've been tricking you a bit: postln is actually a Function, but a special kind, explained later.
(
   var greeter =
   {
      arg name, greeting = "Hello";
      postln( greeting + name );
   };

   greeter.value( "Samantha" );
   greeter.value( "Jermain", "Goodbye" );
   greeter.value( name:"Myung-Whun" );
   greeter.value( greeting:"Bienvenue", name:"Marcel" );
   nil;
)
Any value can be used as a parameter, as long as the Function expects it. In fact, even Functions can be used as parameters for Functions!