home/ atoms/ sc-variables-global-local

SuperCollider scopes variables three ways: local (var) vanish with their block; single-letter and environment (~) names persist across the session

SuperCollider has three variable scopes. Local variables are declared with var at the top of a code block and cease to exist once that block finishes — reading one outside its block yields nil or an error. Single lowercase-letter variables (a–z, with s conventionally reserved for the server) are ‘global’: once assigned they persist across blocks, patches, and even other SC documents until SC quits, but being shared globally they must be used with care in a multi-voice set. Tilde-prefixed environment variables (~freq, ~synth) live in the currentEnvironment and are accessible anywhere that environment is active; setting ~alpha = nil removes the name from the environment. Because separately evaluated blocks don’t share locals, live coding relies on ~ names (or single-letter globals) to carry state between evaluations — and ProxySpace exploits this by overriding the environment so that ~names become NodeProxies. Names must start with a lowercase letter and contain only letters, digits, and underscores.

Examples

~myFreq = 440;        // environment var — survives block exit
(
var temp = 660;       // local — gone after the closing )
temp.postln;          // 660 inside the block
)
temp;                 // nil/error — gone
~myFreq;              // still 440
currentEnvironment;   // shows ~myFreq is set
~myFreq = nil;        // removes it from the environment

Assessment

Predict the Post window output of: (1) ~x = 10; (2) (var x = 5; x.postln;) (3) x;. Explain why reading a var outside its block fails and rewrite the case using an environment variable. Name one hazard of single-letter globals in a multi-voice live set.

“vs.Lo cal Thevariablesyouhaveseenuptonow(thesinglelowercasel”
corpus · a-gentle-introduction-to-supercollider-bruno-ruviaro · chunk 3
“may be loosely called “global variables,” because once declared, they will work “globally” anywhere in the patch, in other patches, even in other SC documents, until you”
corpus · a-gentle-introduction-to-supercollider-ruviaro-archive-org-c · chunk 3
“~alpha = pi; // set env. variable ~alpha to pi currentEnvironment; // see current Environment again: ~alpha is set ~freq = 800; // set another environment variable”
corpus · the-supercollider-book-official-code-examples-scbookcode-gpl · chunk 142