How To Cog - Chapter 2.7 - Arrays

Arrays

You'll often need to access a variable without knowing its 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. The array index number is used to find the variable so many variables down from the top of the list.

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.

In this example, values are assigned to each array variable:

Symbols:

int     array0=0     local
int     array1=1     local
int     array2=2     local
int     array3=3     local
int     array4=4     local
int     array5=5     local


Code:

#-----------------------------
startup:
   Sleep(1);
   PrintInt(array0[4]);

Return;
#-----------------------------

That 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. 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 yellow.

Arrays are most useful when used in combination with loops. If you have ten surfaces (0 - 9) defined in the symbols section and you need to change their material, you might use something like this:

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

Return;
#-----------------------------

One line of code did the work that would have taken ten lines if arrays and loops had not been used.


Previous: Loops Up: How To Cog Next: Writing Cogs
  • Create:
This page was last modified 15:50, 14 April 2006.   This page has been accessed 1,545 times.