Function:
Filter:
Classes | Core > Kernel

Function : AbstractFunction : Object

Implements a function
Source: Function.sc

Description

A Function is a reference to a FunctionDef and its defining context Frame. When a FunctionDef is encountered in your code it is pushed on the stack as a Function. A Function can be evaluated by using the 'value' method. See the Functions help file for a basic introduction.

Because it inherits from AbstractFunction, Functions respond to math operations by creating a new Function.

See AbstractFunction: Function Composition for function composition examples.

Because Functions are such an important concept, here some examples from related programming languages with functions as first class objects:

Related Keywords

thisFunction

The global pseudo-variable thisFunction always evaluates to the current enclosing Function.

NOTE: Be aware of inline optimizations which will be reflected in the value of thisFunction.

See also: thisFunctionDef

Class Methods

Inherited class methods

Instance Methods

Access

.def

Get the definition ( FunctionDef ) of the Function.

.isClosed

returns true if the function is closed, i.e. has no external references and can thus be converted to a compile string safely.

Evaluation

.value( ... args)

Evaluates the FunctionDef referred to by the Function. The Function is passed the args given.

.valueArray( ... args)

Evaluates the FunctionDef referred to by the Function. If the last argument is an Array or List, then it is unpacked and appended to the other arguments (if any) to the Function. If the last argument is not an Array or List then this is the same as the 'value' method.

A common syntactic shortcut:

.valueEnvir( ... args)

As value above. Unsupplied argument names are looked up in the current Environment.

.valueArrayEnvir( ... args)

Evaluates the FunctionDef referred to by the Function. If the last argument is an Array or List, then it is unpacked and appended to the other arguments (if any) to the Function. If the last argument is not an Array or List then this is the same as the 'value' method. Unsupplied argument names are looked up in the current Environment.

.valueWithEnvir(envir)

Evaluate the function, using arguments from the supplied environment. This is slightly faster than valueEnvir and does not require replacing the currentEnvironment.

.functionPerformList(selector, arglist)

For Function, this behaves the same as valueArray(arglist). It is used where Functions and other objects should behave differently to value, such as in the object prototyping implementation of Environment.

.performWithEnvir(selector, envir)

Arguments:

selector

A Symbol representing a method selector.

envir

The remaining arguments derived from the environment and passed as arguments to the method named by the selector.

.performKeyValuePairs(selector, pairs)

Arguments:

selector

A Symbol representing a method selector.

pairs

Array or List with key-value pairs.

.loop

Repeat this function. Useful with Task and Clocks.

.defer(delta)

Delay the evaluation of this Function by delta in seconds on AppClock.

This is equivalent to AppClock.sched(0, function) unless delta is nil. In that case the function is only scheduled if current code is not running on AppClock, otherwise the function is evaluated immediately.

.dup(n: 2)

Return an Array consisting of the results of n evaluations of this Function.

!(n)

From superclass: Object

equivalent to dup(n)

.sum(n: 2)

return the sum of n values produced.

.choose

evaluates the function. This makes it polymorphic to SequenceableCollection, Bag and Set.

.bench(print: true)

Returns the amount of time this function takes to evaluate. print is a boolean indicating whether the result is posted. The default is true.

.fork(clock, quant, stackSize)

Returns a Routine using the receiver as it's function, and plays it in a TempoClock.

.forkIfNeeded(clock, quant, stackSize)

If needed, creates a new Routine to evaluate the function in, if the message is called within a routine already, it simply evaluates it.

.block

Break from a loop. Calls the receiver with an argument which is a function that returns from the method block. To exit the loop, call .value on the function passed in. You can pass a value to this function and that value will be returned from the block method.

.thunk

Return a Thunk, which is an unevaluated value that can be used in calculations

.flop

Return a function that, when evaluated with nested arguments, does multichannel expansion by evaluating the receiver function for each channel. A flopped function responds like the "map" function in languages like Lisp. The new function always returns an array.

.flop1

Same as flop, return only an array if the arguments also contains an array. This can be used to implement Multichannel Expansion.

.envirFlop

This method is kept for backward compatibility. Use flop instead.

.inEnvir(envir)

returns an "environment-safe" function. See Environment for more details. Note that the function returned takes no keyword arguments.

.inEnvirWithArgs(envir)

Like inEnvir, but returns a function which takes keyword arguments. Building this function makes a call to the interpreter and is less efficient than inEnvir

.case( ... cases)

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. Unlike Object-switch, this is inlined and is therefore just as efficient as nested if statements.

.matchItem(item)

Interface shared with other classes that implements pattern matching. See also: matchItem. Function.matchItem evaluates the function with the item as argument, expecting a Boolean as reply.

See also matchItem.

.performDegreeToKey(scaleDegree, stepsPerOctave: 12, accidental: 0)

use a function as a conversion from scale degree to note number. See also SequenceableCollection and Scale

Exception Handling

For the following two methods a return ^ inside of the receiver itself cannot be caught. Returns in methods called by the receiver are OK.

See also Exception Handling Examples and Exception for more information on how to handle exceptions.

.try(handler)

Executes the receiver. If an exception is thrown the catch function handler is executed with the error as an argument. handler itself can rethrow the error if desired.

.protect(handler)

Executes the receiver. The cleanup function handler is executed with an error as an argument, or nil if there was no error. The error continues to be in effect.

Scheduling

.awake(beats, seconds, clock)

This method is called by a Clock on which the function was scheduled when its scheduling time is up. It calls -value, passing on the scheduling time in beats as an argument.

Arguments:

beats

The scheduling time in beats. This is equal to the current logical time (Thread: -beats).

seconds

The scheduling time in seconds. This is equal to the current logical time (Thread: -seconds).

clock

The clock on which the object was scheduled.

Returns:

The value returned by the function's -value. A caller clock uses this value to reschedule the function.

Audio

.play(target, outbus: 0, fadeTime: 0.02, addAction: 'addToHead', args)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/asDefName.sc

Play a Synth from UGens returned by the function. The function arguments become controls that can be set afterwards.

This works as follows: play wraps the UGens in a SynthDef and sends it to the target. When this asynchronous command is completed, it creates one synth from this definition.

Arguments:

target

A Node, Server, or Nil. A Server will be converted to the default group of that server. Nil will be converted to the default group of the default Server.

outbus

A bus number that determines the output channel. This is equivalent to Out.ar(outbus, signal). The default is 0.

fadeTime

Crossfade time for attack and release of the synth. The default is 0.02 seconds, which is just enough to avoid a click.

addAction

The add action for the synth. For a list of valid addActions see Synth

args

An array of key value pairs of control names and control values which are used when starting the synth.

NOTE: Some UGens are added in this process.
  • an Out UGen for playing the audio to the first audio busses. If the function returns an Out UGen, this is omitted.
  • an envelope with a \gate control for releasing and crossfading. If the function provides its own releasable envelope, this is omitted.

Many of the examples make use of the Function.play syntax. Note that reusing such code in a SynthDef requires the addition of an Out ugen.

Function.play is often more convenient than SynthDef.play, particularly for short examples and quick testing. The latter does have some additional options, such as lagtimes for controls, etc. Where reuse and maximum flexibility are of greater importance, SynthDef and its various methods are usually the better choice.

.scope: METHOD NOT FOUND!

As play above, and calls Server-scope to open a scope window in which to view the output.

Arguments:

numChannels

The number of channels to display in the scope window, starting from outbus. It automatically reflects the number of channels.

outbus

The output bus to play the audio out on. This is equivalent to Out.ar(outbus, theoutput). The default is 0.

fadeTime

A fadein time. The default is 0.05 seconds, which is just enough to avoid a click.

bufsize

The size of the buffer for the ScopeView. The default is 4096.

zoom

A zoom value for the scope's X axis. Larger values show more. The default is 1.

.plot: METHOD NOT FOUND!

NOTE: See plot for a general reference on plotting

Calculates duration in seconds worth of the output of this function asynchronously, and plots it in a GUI window. Unlike play and scope it will not work with explicit Out Ugens, so your function should return a UGen or an Array of them. The plot will be calculated in realtime.

Arguments:

duration

The duration of the function to plot in seconds. The default is 0.01.

target

The server, synth or group where the signal is picked up. See asTarget.

bounds

An instance of Rect or Point indicating the bounds of the plot window.

minval

the minimum value in the plot. If not specified, the signal's minimum is used.

maxval

the maximum value in the plot. If not specified, the signal's maximum is used.

separately

If set to true, for multichannel signals use separate value display ranges, unless minval or maxval is specified already.

.asBuffer(duration: 0.01, target, action, fadeTime: 0)

Calculates duration in seconds worth of the output of this function asynchronously, and returns it in a Buffer of the number of channels. This method immediately returns a buffer, which takes duration seconds to become filled with data asynchronously. Then the action function is called.

Arguments:

duration

The duration of the function to plot in seconds. The default is 0.01.

target

The synth or group after which the synth runs (see asTarget). The default is the default group of Server.default.

action

A function that is called when the buffer is filled. It is passed the buffer as argument.

fadeTime

A fade in and out time in seconds. Only when greater than zero, an envelope is applied to the signal to avoid clicks (default: 0).

Discussion:

.loadToFloatArray(duration: 0.01, target, action)

Write a UGen function to a file and then load it into a FloatArray.

Arguments:

duration

Amount of data to record in seconds

target

A server, synth, or group where to place the synth that plays the function

action

A function to call when writing is finished.

.getToFloatArray(duration: 0.01, target, action, wait: 0.01, timeout: 3)

Stream the function audio values to the client using a series of getn messages and put the results into a FloatArray.

Arguments:

duration

Amount of data to record in seconds

target

A server, synth, or group where to place the synth that plays the function

action

A function to call when writing is finished.

wait

The amount of time in seconds to wait between sending getn messages. Longer times are safer. The default is 0.01 seconds which seems reliable under normal circumstances. A setting of 0 is not recommended.

timeout

The amount of time in seconds after which to post a warning if all replies have not yet been received. the default is 3.

Discussion:

For a discussion of the difference between getToFloatArray and loadToFloatArray, see Buffer: -getToFloatArray and Buffer: -loadToFloatArray.

Conversion

.asSynthDef(rates, prependArgs, outClass: 'Out', fadeTime, name)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/asDefName.sc

Returns a SynthDef based on this Function, adding a Linen and an Out ugen if needed.

Arguments:

rates

An Array of rates and lagtimes for the function's arguments (see SynthDef for more details).

prependArgs

arguments

outClass

The class of the output ugen as a symbol. The default is \Out.

fadeTime

a fadein time. The default is 0.

name

the name of the SynthDef

.asDefName

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/asDefName.sc

Performs asSynthDef (see above), sends the resulting def to the local server and returns the SynthDefs name. This is asynchronous.

.asRoutine

Returns a Routine using this as its func argument.

.r

Returns a Routine using this as its func argument.

.p

Returns a Prout using this as its func argument.

This is useful for using ListComprehensions in Patterns:

Bela

.belaScope(scopeChannel, target, numChannels, outbus: 0, fadeTime: 0.02, addAction: 'addToHead', args)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Audio/Bela/BelaScope.sc

Like Function: -scope, plays and scopes this Function, but using Bela's Oscilloscope (see BelaScope for required setup). This Function's output bus is monitored right after the generated Synth.

Arguments:

scopeChannel

Bela's oscilloscope channel to start scoping on. This has to be a non-negative number, and can't be changed after scoping starts.

target

A Node, Server, or Nil. A Server will be converted to the default group of that server. Nil will be converted to the default group of the default Server.

NOTE: this Function's play target needs to be on a Server that supports BelaScope
numChannels

Number of channels to scope, from this Function's output channels. Defaults to this Function's output channels.

outbus
fadeTime
addAction
args

See Function: -scope

Returns:

Like Function: -play, a Synth playing this function. When that synth is freed, so will be its monitor.

Inherited instance methods

Undocumented instance methods

.archiveAsCompileString

.archiveAsObject

.argNames

From extension in /usr/local/share/SuperCollider/SCClassLibrary/JITLib/ProxySpace/wrapForNodeProxy.sc

.checkCanArchive

.cmdPeriod

.defaultArgs

From extension in /usr/local/share/SuperCollider/SCClassLibrary/JITLib/ProxySpace/wrapForNodeProxy.sc

.doOnCmdPeriod

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extSystemActions.sc

.doOnError

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extSystemActions.sc

.doOnServerBoot(server)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extSystemActions.sc

.doOnServerQuit(server)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extSystemActions.sc

.doOnServerTree(server)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extSystemActions.sc

.doOnShutDown

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extSystemActions.sc

.doOnStartUp

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extSystemActions.sc

.get(prevVal)

.handleError(error)

.isFunction

.makeFlopFunc

.numArgs

.numVars

.postString

From extension in /usr/local/share/SuperCollider/SCClassLibrary/JITLib/Patterns/extFunction.sc

.prTry

.prepareForProxySynthDef

From extension in /usr/local/share/SuperCollider/SCClassLibrary/JITLib/ProxySpace/wrapForNodeProxy.sc

.set( ... args)

.shallowCopy

.transformEvent(event)

.update(obj, what ... args)

.varArgs

Examples

Exception Handling Examples