Variables and Scope#
Here we encounter the first inconvenience.
In (SC), there are some special pre-defined variables.
Each single character variable [a-z]
is pre-defined and globally available.
They are called interpreter variables or global variables.
The Local Server Variable
By default, the variable s
holds a reference to the local audio server.
If you come from a modern programming language, this is strange.
However, it is often helpful for prototyping in (SC).
s
is a very special global variable because it holds a reference to the default local server.
Therefore, to start/boot the audio server, we evaluate:
s.boot;
No one stops you from overwriting s
, but I would not recommend it.
As already mentioned, to define a code block, we use round brackets.
We can use x
before defining it because it is already defined for us.
(
x = 10;
x;
)
Evaluating
number = 10;
results in an error because number
is undefined.
The code evaluation works similar to the cell evaluation in a Python
Jupyter notebook, but variables (except for the single character) are local.
Local and global variables are not saved in the current environment.
Local variables only live inside their block and global/interpreter variables are constructed and saved prematurely.
You can print out the current environment by just accessing it:
currentEnvironment;
The following code does not work without round brackets
var number = 10;
number;
because number
is locally defined within the scope of a single line!
If we use brackets
(
var number = 10;
number;
)
number
is local within the brackets.
Note that we have to execute the whole block; otherwise number
is still local within one line.
To define our own global variable, we have to use ~
in front of the variable name, for example:
~number = 10;
~number;
works just fine.
These variables are called environment variables and they are stored in currentEnvironment
.
We can also use single character local variables. The following code returns 13
x = 10;
(
x = x + 3;
x;
)
but the code below returns 3
.
x = 10;
(
var x = 0;
x = x + 3;
x;
)
In summary, there are three types of variables:
(global) single character interpreter variables, e.g.,
x
,y
(global) environment variables, e.g.
~number
(local) local variables
var variable = 10;
As their name indicates, variables can be reassigned, and due to the dynamic type system, we can give them any new value at any time.
Exponential Operator
Like Python
, sclang
supports the exponential operator **
.
2**4 // 16.0