Arrays (ZScript)

From ZCWiki

Jump to: navigation, search

An array is a group of values of the same data type, such as a group of ten integers. The whole array has a single name, and the individual values in the array (called elements) are accessed by using an integer index. Arrays are useful because they allow you to store several items of related information in a convenient fashion, and it is relatively easy to step through all the elements in an array.

[edit] Syntax

Like other variables, arrays must be declared before they can be used. Declare an array as follows:

data-type name[max-elements];

data-type is one of the following types:

  • int - an integer.
  • float - a floating point number (a number with a decimal point).
  • bool - a boolean value which is either true or false.
  • npc - a pointer (a kind of reference) to a Non-playing Character (such as an enemy) on the screen.
  • ffc - a pointer to a freeform combo on the screen.
  • item - a pointer to an item on the screen.

You can define the name to be any useful name, as long as it does not contain any illegal characters (spaces, characters used as operators, etc.). Underscores are legal characters.

max-elements is an integer specifying the maximum number of elements the array can hold.

The following example declares a 5-element array of integers named "myArray".

int myArray[5];

[edit] Usage

You refer to the elements in an array by specifying the index of the element you wish to access. The index is enclosed in square brackets. Note that the index starts at 0. In other words, the index of the 1st element in the array is 0, while the index of the last element in the array is 1 less than the array's size. For example, for an array "myArray" that holds 5 elements, the last element is myArray[4]. See the examples.

Take caution when using arrays of type npc, ffc, and item, as you'll need to do some extra initialization and checking. For instance, if you declare an array of type ffc, you still need to use the Screen->LoadFFC() method to point your array elements to the FFCs on the screen. Additionally, you may get unexpected results if you have an array of npcs, but the number of NPCs on the screen changes while your script is running (resulting in a reference to a non-existent NPC).

[edit] Examples

The following example declares a 5-element array of integers, and then sets each element to a value that is twice that element's index.

ffc script ArrayTest{
  void run(){
    int myArray[5];
    int index; 

    // Initialize all the elements
    // in the array.
    for(index=0; index<5; index++){
      myArray[index] = index * 2;
    }

    // Write the array values to
    // the logfile.
    for(index=0; index<5; index++){
      Trace(index);
      Trace(myArray[index]);
    }

  }
}
Personal tools