Library functions: Std, Math, other - Programming for Musicians and Digital Artists: Creating music with ChucK (2015)

Programming for Musicians and Digital Artists: Creating music with ChucK (2015)

Appendix B. Library functions: Std, Math, other

In chapter 2 you first learned about the Standard library (Std) and some of the tools (functions) available in that collection. You also learned about the Math library and have since been using many functions from both Std and Math. In later chapters you encountered some of the Machine VM functions. You’ve used me.dir() and some other built-in ChucK library and class methods.

There are many other useful tools related to shreds, objects, and other classes built into ChucK. The tables in this appendix list and briefly describe them. Because the appendix is basically only a list, we won’t show you how you might use each function. Nor will we introduce each table. Consider joining one of the ChucK forums or mailing lists (at http://chuck.stanford.edu/community/) for more information on using the full power of ChucK.

B.1. The ChucK Standard Library

You use these in this way: Std.functionName(args).

Example: Std.abs(x) => float myAbs;

Table B.1. Std functions for converting and dealing with basic data types

Function name and arguments

What the function does

int abs(int value);

Returns absolute value of integer.

float fabs(float value);

Returns absolute value of floating point number.

float sgn(float value);

Computes sign of input as -1.0 (neg), 0, or 1.0 (pos).

int atoi(string value);

Converts ASCII (string) to integer (int).

string itoa(int value);

Converts integer to ASCII (string character).

int ftoi(float value);

Converts floating-point number to integer (by truncation).

float atof(string value);

Converts ASCII (string) to floating-point value (float).

string ftoa(float value, int precision);

Converts float to ASCII (string character) (precision = decimal points).

Table B.2. Std functions for dealing with music and sound quantities

Function name and arguments

What it does

float mtof(float value);

Converts a MIDI note number to frequency (Hz). Note the input value is of type float (supports fractional note number).

float ftom(float value);

Converts frequency (Hz) to MIDI note number space.

float powtodb(float value);

Converts signal power ratio to decibels (dB).

float rmstodb(float value);

Converts linear amplitude to decibels.

float dbtopow(float value);

Converts decibels to signal power ratio.

float dbtorms(float value);

Converts decibels to linear amplitude.

Table B.3. More Std functions (system power tools); be wary!

Function name and arguments

What it does

string getenv(string key);

Returns the value of an environment variable (such as PATH).

int setenv(string key, string value);

Sets environment variable key to value.

int system(string cmd);

Passes cmd to be executed by the system shell.

Note

To use the system command function, you must run ChucK with the flag

--caution-to-the-wind

This tells ChucK that you’re going to be responsible with your code, because it’s possible to delete files or wreak other mayhem using system calls. In command-line ChucK, you specify the -–caution-to-the-wind flag. You can’t currently use this in the miniAudicle, which is largely for your protection. Consult appendix G, “ChucK on the command line,” to learn how to use ChucK in this way.

B.2. The ChucK Math library

You call all of these functions using Math.functionName(args).

Example: Math .sin(x) => float mySine;

Table B.4. Math library: trigonometric and transcendental functions

Function name and arguments

What it does

float sin(float x);

Computes the sine of x.

float cos(float x);

Computes the cosine of x.

float tan(float x);

Computes the tangent of x.

float asin(float x);

Computes the arc sine of x.

float acos(float x);

Computes the arc cosine of x.

float atan(float x);

Computes the arc tangent of x.

float atan2(float y, float x);

Computes the principal value of arc tangent of y/x using the signs of both arguments to determine the quadrant of the return value.

float sinh(float x);

Computes the hyperbolic sine of x.

float cosh(float x);

Computes the hyperbolic cosine of x.

float tanh(float x);

Computes the hyperbolic tangent of x.

float hypot(float x, float y);

Computes the square root of (x2 + y2); can be seen as computing the hypotenuse of a right triangle with sides x and y or the magnitude of a two-dimensional vector (x, y).

float pow(float x, float y);

Computes x taken to the y-th power.

float sqrt(float x);

Computes the positive square root of x (x >= 0).

float exp(float x);

Computes ex, the base-e exponential of x.

float log(float x);

Computes the natural logarithm of x.

float log2(float x);

Computes the logarithm of x to base 2.

float log10(float x);

Computes the logarithm of x to base 10.

Table B.5. Math library: random number functions

Function name and arguments

What it does

int random();

Generates random integer between 0 and Math.RANDOM_MAX.

int random2(int min, int max);

Generates random integer in the range [min, max].

float randomf();

Generates random floating-point number in the range [0, 1].

float random2f(float min, float max);

Generates random floating point number in the range [min, max].

Table B.6. Math library: operations and calculations on numbers

Function name and arguments

What it does

float floor(float x);

Rounds to largest integral value (returns float) not greater than x.

float ceil(float x);

Rounds to smallest integral value (returns float) not less than x.

float round(float x);

Rounds to nearest integral value (returns float).

float trunc(float x);

Rounds to largest integral value (returns float) no greater in magnitude than x.

float fmod(float x, float y);

Computes the floating point remainder of x / y.

float remainder(float x, float y);

Computes the value r such that r = x - n * y, where n is the integer nearest the exact value of x / y. If there are two integers closest to x / y, n shall be the even one. If r is zero, it is given the same sign as x.

float min(float x, float y);

Chooses lesser of two values.

float max(float x, float y);

Chooses greater of two values.

int nextpow2(int x);

Computes the integral (returned as int) smallest power of 2 greater than the value of x.

float isinf(float x);

Tests if x is infinity.

float isnan(float x);

Tests if x is not a number.

You access the constants in table B.7 using Math.constantName.

Example: 0.75* Math.PI => float threeFourthsPI;

Table B.7. Math library: constants

Function name and arguments

What it is

float PI;

Constant PI; use as Math.PI.

float TWO_PI;

Constant PI*2; example usage: Math.TWO_PI.

float e; // also E

Euler’s constant, base of natural logarithm; same as Math.exp(1); use as: Math.e or Math.E.

complex i; // also j, I, or J

Square root of -1, the imaginary number i as a complex value; use as Math.i or Math.j or Math.I or Math.J.

int RANDOM_MAX;

Max value returned by Math.random().

B.3. Virtual machine commands and functions

You access these using Machine.functionName(args).

Example: Machine.add ("foo.ck");.

Table B.8. VM commands and functions

Function name and arguments

What it does

int add(string path);

Compiles and sporks a new shred from file at path into the VM now and returns the shred ID.

int spork(string path);

Same as add.

int remove(int id);

Removes shred from the VM by shred ID (returned by add/ spork).

int replace(int id, string path);

Replaces shred with new shred from file.

int status();

Displays current status of the VM.

void crash();

Literally causes the VM to crash, a last resort; use with care.

B.4. Shred object functions

Using an instance of the Shred class shredObj, you can access these with shredObj.functionName(args). Example: shredObj.dir(-2) @=> string aPath2Up;. The most commonly used instance of Shred is me, which corresponds to the currently running shred, for example: me.dir() @=> string path. Additionally, the spork operator (introduced in chapter 8) returns an instance of Shred, with which you can also use these methods. Lastly, a static member function, Shred.fromid(), returns a Shred object corresponding to a given shred ID.

Table B.9. Shred object functions

Function name and arguments

What it does

Shred.fromId(int id)

Returns shred object corresponding to id.

int id();

Returns the ID number of the shred.

void yield();

Causes the shred to temporarily discontinue processing and allows other active shreds to run.

void exit();

Schedules the shred for immediate termination.

int running();

Returns 1 if shred is still running, 0 otherwise.

int done();

Returns 1 if shred has finished, 0 otherwise; except in rare cases, this is the opposite of done().

int args();

Returns the number of command-line arguments.

string arg(int num);

Returns command-line argument at position num.

string me.dir();

Returns the directory from whence this shred came.

string me.dir(int numUp);

Returns numUp directories from whence this shred came; numUp can be positive or negative, with the same result.

B.5. String object functions

ChucK allows for many different manipulations of strings using these functions. In addition to these functions, strings can be combined using the + operator.

Example: "foo" + "bar" @=> string val; // val == "foobar"

Table B.10. String object functions

Function name and arguments

What it does

int length();

Returns number of characters in the string.

int charAt(int i);

Returns ASCII value of character at position i.

int setCharAt(int i, int c);

Sets character at position i to ASCII value c.

int find(int c);

Returns position of first character matching c in the string. Returns -1 if no matching character is found.

int find(int c, int p);

Returns position of first character matching c in the string, at or after position p. Returns -1 if no matching character is found.

int find(string s);

Returns position of first substring matching s in the string. Returns -1 if no matching substring is found.

int find(string s, int p);

Returns position of first substring matching s in the string, at or after position p. Returns -1 if no matching substring is found.

int rfind(int c);

Returns position of last character matching s in the string. Returns -1 if no matching character is found.

int rfind(int c, int p);

Returns position of last character matching c in the string, at or before position p. Returns -1 if no matching character is found.

int rfind(string s);

Returns position of last substring matching s in the string. Returns -1 if no matching substring is found.

int rfind(string s, int p);

Returns position of last substring matching s in the string, at or before position p. Returns -1 if no matching substring is found.

string substring(int i);

Returns a new string with the substring from position i to the end of the string.

string substring(int i, int len);

Return a new string with the substring from position i of length len, or to the end of the string.

void insert(int i, string str);

Inserts str at position i in the string, shifting existing string at i to after str.

void replace(int i, string str);

Replaces characters from position i to end of string with str.

void replace(int i, int len, string str);

Replaces len characters starting from position i with str.

void erase(int i, int len);

Removes len characters from string, starting at position i.

string ltrim();

Returns new string with leading spaces removed.

string rtrim();

Returns new string with trailing spaces removed.

string trim();

Returns new string with leading and trailing spaces removed.

string upper();

Returns new string with all letters in uppercase.

string lower();

Returns new string with all letters in lowercase.

B.6. Array object functions

Arrays in ChucK are easy to manipulate, adding and removing elements as needed. For example, you can append items to an array using the << operator:

[64, 65, 60, 59] @=> int notes[];

notes << 58 << 60; // notes is now [64, 65, 60, 59, 58, 60]

Table B.11. Array-supported functions

Function name and arguments

What it does

int size();

Number of elements in the array.

int size(int n);

Sets number of elements in the array to n. Fills any new elements with default values (0 for int and float, 0::second for dur and time, null for strings and objects).

void popBack();

Removes last element in array.

void clear();

Removes all elements in array.