Sporkl Variables


Variables in Sporkl are objects which store values. Variables have a type and a name associated with them. To use a variable in a Sporkl program, it must first be declared, for example:

int i;

declares a variable of type int called "i". Scalar (non-array) variables of type byte, int, float, string, rgb, and input can be assigned values using the "=" assignment operator. Array variables, and variables of type image, must use functions provided to assign values.

Scope

Variables are visible to the program after declaration within the same code block (either the "top level" or a section of code enclosed within brackets "{}") or descendent code blocks. The exception to this is when a variable is declared as "global", for example:

global int i;
global array byte b;

Global variables are visible and may be modified anywhere in the program, including within the bodies of all functions in the program, as long as they are accessed after their declaration has been executed in the program flow, otherwise an error will occur.

Declarations

All variables must be declared before use. Declarations may either be in the form of a program statement, or in the header of a function definition. The full form of a declaration in program statement form is as follows:

[global] [array] <data type> <list of variable names..>

The form of a declaration in a function definition header is:

[array] <data type> [&] <variable name>

The "&" in the above indicates that the variable is to be passed by reference rather than by value.

Arrays

Arrays are a series of basic data type containers placed together in a continuous block of memory. For example, you may have an integer array of length 10, which is an object that contains 10 integer values, each of which is called an "element" of the array. Individual elements of an array can be accessed using the indexing ("[]") operator. For example, to get or set the value of the fourth element in an array called "a", you would write "a[3]". It is "3" instead of "4" because array element numbering starts at "0". So, an array of length 10 would contain elements indexed "0" - "9". Attempting to access an array element with an index value outside of the valid range results in a runtime error.

You declare an array by adding the word "array" before the basic data type, for example:

array int a;

declares an integer array variable called "a".

Note: arrays are always initialized to length zero, or "empty". You must explicitly resize them using, for example, resize_array() or push_back().

Multidimensional arrays are not supported, so you may not, for example, declare an array of arrays.




( <-- Back to Sporkl documentation home )




sporkforge