Arrays in Cog


In programming, you'll often need to access a variable without knowing it's name. Arrays allow you store values in an array of variables. Then you can use a variable's index number instead of its name to retrieve the value of the variable.

Cog does not have a true array system like most programming languages. Instead, all the variables in the array must be listed consecutively in the symbols section.1 The array index number is used find the variable so many variables down from the top of the list.

Note that if you try to access an array variable that does not exist, JK will crash. Arrays aren't unstable, you just have to be careful when using them.

Here's a typical list of variables used in an array:

int     array0     local
int     array1     local
int     array2     local
int     array3     local
int     array4     local
int     array5     local
By convention, all variables in the array have the same name and end with the index number that is used to find them.

To retrieve the value of one of the variables in the array, first list the top variable in the array. In this case it's array0. After that variable, put the array index number enclosed in brackets. So you would use array0[5] to access the array5 variable.

Now lets assign a value to each of the array variables:

int     array0=0     local
int     array1=1     local
int     array2=2     local
int     array3=3     local
int     array4=4     local
int     array5=5     local
And in the code section, the value of the array4 will be printed:
#-----------------------------
startup:
   Sleep(1);
   PrintInt(array0[4]);

Return;
#-----------------------------
That code will print 4 to the screen on startup.

It's convenient to have the variable's name match up with the index number that is used to call it. IE, array4 is the fourth variable in the array. But variables don't have to be named that way. For example:

int     var        local
int     red        local
int     green     local
int     blue       local
int     yellow    local
int     orange   local
In this case, var[4] can be used to access the variable, yellow.

Arrays are most useful when used in combination with loops. Lets say you have ten surfaces defined in the symbols section and you need to change their material. Look at this example:

#-----------------------------
activated:
   for(i=0; i < 11; i=i+1) SetSurfaceMat(surf0[i], newmat);

Return;
#-----------------------------
Here, one line of code did the work that would have taken ten lines if arrays and loops had not been used.

1 Array variables can be declared in the code section, but that's not recommended.

*Special thanks to Fardreamer for information on Cog's array system.*