Arrays

From TrainzOnline
(Difference between revisions)
Jump to: navigation, search
m (Categories)
 
(One intermediate revision by one user not shown)
Line 42: Line 42:
 
  words[3] = "sentences"
 
  words[3] = "sentences"
 
  objects[0] = me;
 
  objects[0] = me;
  myObjects[2] = Router,GetGameObject("my sibling");
+
  myObjects[2] = Router.GetGameObject("my sibling");
  
 
{{MethodHeader|Array Methods}}
 
{{MethodHeader|Array Methods}}
Line 188: Line 188:
  
 
==See Also==
 
==See Also==
 +
 +
 +
=Categories=
 +
[[Category:TrainzScript]]

Latest revision as of 10:53, 24 April 2019

Contents

[edit] Declaration, Initialisation & Population

  • Arrays need to be declared and initialised before they can be accessed, and it will usually be necessary to populate the array with meaningful data.

Declaration
  • A declaration reserves memory for the variable and allocates a name for that particular array. This is analogous to a housing developer buying a site and reserving it for future construction.
  • To declare an array you must first define the type of object which the array will contain, followed by opening and closing square braces and the name you will use to reference the array variable.
  • Just as residential developments can consist of any building type, arrays can consist of almost any class, including classes which you have defined yourself.
Vehicle[] vehicles;
int[] numberList;
string[] words;
GameObject[] objects;
MyOwnClass[] myObjects;
Initialisation
  • In the same way that a developer must decide how many units he wants to build, you must decide how many members your array will initially be able to contain. You will be able to make the array larger or smaller later, for now you are just setting the initial size.
  • To initialise the array you use the keyword new, followed by the class of object that the array is to contain and the initial number of members in square brackets.
vehicles = new Vehicle[5];
numberList = new int[10];
words = new string[2];
objects = new GameObject[3];
myObjects = new MyOwnClass[7];
  • It is possible, and often convenient, to declare and initialise the array in a single statement:
Vehicle[] vehicles = new Vehicle[5];
int[] numberList = new int[10];
string[] words = new string[2];
GameObject[] objects = new GameObject[3];
MyOwnClass[] myObjects = new MyOwnClass[7];
Population
  • We now have a plot of land and some completed buildings but it will still be meaningless to call at an individual house because no-one will be living there.
  • You can populate the individual elements by assigning a value to an indexed position in the array. The syntax for this is:
vehicles[0] = GetMyTrain().GetVehicles[3];
numberList[0] = 0;
words[3] = "sentences"
objects[0] = me;
myObjects[2] = Router.GetGameObject("my sibling");
Array Methods
  • A further shortcut is to use a method which returns an array to initialise and populate your array in a single statement. Often the same statement can also contain the declaration:
Vehicle[] vehicles = World.GetVehicleList();
int[] numberList = GetNumberList(1,10);
string[] words = Str.Tokens("comma,separated,list",",");
  • You can write your own methods to return arrays:
int[] GetNumberList(int start, int count) {
  int[] result = new int[0];
  int i;
  for (i = start; i < count; i++) {
    result[result.size()] = i;
  }
  return result;
}

[edit] Array Operators

Appending to an Array
  • This is a syntax which allows you to increase the size of a properly initialised array by adding a new member to the end. Since array indexing starts at zero, the last member will always be array[array.size() - 1].
  • Trying to read from array[array.size()] will result in a range error because you are attempting to access a location which does not exist.
  • Assigning to array[array.size()] however, will create a new member and increment the number of items in the array.
vehicles[vehicles.size()] = me;
Indexing
  • A subscript enclosed in square brackets serves to define an individual item within an array. The notation will only be meaningful if that particular item has a value assigned. Assuming that this is the case when it isn't is a common error, and one that can be very difficult to find.
  • Given these statements:
int[] numbers = new int[3];
numbers[0] = 0;
numbers[2] = 2;
  • numbers[0] will return zero as an integer
  • numbers[2] will return the value 2
  • numbers[1] however will return null since no value has been assigned to that particular item.
  • Array indexing starts at zero (don't ask why) and finishes at array.size() - 1.


Range Indexing
  • Whilst it is straightforward to erase a value from an array by assigning it to null, this doesn't affect the size of the array itself.
  • Given these statements:
int[] numbers = new int[3];
numbers[0] = 0;
numbers[1] = 1;
numbers[2] = 2;
  • Making the assignment numbers[2] = null will clear out the value but the array will still contain 3 items.
  • You can delete items and reduce the size of the array at the same time by specifying a range index like this:
numbers[0,1] = null;
  • The first index is the position of the item to remove and the second is one greater than the position of the last item.
numbers[0,1] = null removes the first item
numbers[2,3] = null removes the last item
  • Array range indexing is an important tool for use with strings (which are really arrays of characters)


size()
  • array.size() returns a count of the items in the array, this is no guarantee that all of the items have a value.


copy()
  • copy() creates a duplicate of the array, the syntax is:
int[] old = new int[3];
int[] new;
new.copy(old);
  • There is a subtle difference between copying an array and creating a duplicate reference to it by assignment. In the case above, the array new is an entirely separate variable from the array old. Changing the values of one will not affect the other.
int[] old = new int[3];
int[] new;
new = old;
  • will produce a similar result at first glance, but in this case assigning a new value to new[1] will also change the value of old[1]. This is because the assignment effectively creates an alternative name for the same data.

[edit] Code Samples

Array Handling Methods
  • These are example routines which carry out some basic operations on string arrays, all the routines are case sensitive. They can be used for other object types with appropriate modification.
  • Member returns true if the string 's' is contained within the array 'strings'.
public bool Member(string[] strings, string s) {
  int n;
  bool result = false;
  if (strings.size() == 0) {return result;}
  for (n = 0; n < strings.size(); n++) {
    if (s == strings[n]) {
      result = true;
      break;
    }
  }
  return result;
}
  • Add will append string 's' to the end of the array 'strings' as long as 's' is not already present.
public void Add(string[] strings, string s) {
  if (Member(strings,s)) return;
  else {strings[strings.size()] = s;}
}
  • Remove will delete any instance of string 's' from the array and reduce the size of the array accordingly.
public void Remove(string[] strings, string s) {
  int n;
  if (strings.size() == 0) return;
  for (n = 0; n < strings.size(); n++) {
    if (s == strings[n]) {strings[n,n+1] = null;}
  }
}
  • Sort will perform a case sensitive alpha sort of the strings in the array. This is a flagged bubble sort, simple but slow, and is fine for most small arrays. For large arrays you should write your own quicksort method.
public void Sort(string[] strings) {
  int x,y;
  string temp;
  bool flag;
  for (x = 0; x < strings.size(); x++) {
    flag = false;
    for (y = 0; y < strings.size() - 1; y++) {
      if (strings[y] > strings[y + 1]) {
        temp = strings[y + 1];
        strings[y + 1] = strings[y];
        strings[y] = temp;
        flag = true;
      }
    }
    if (!flag) break;
  }
}

[edit] See Also

[edit] Categories

Personal tools