4.4. Accessing Elements in Arrays

Arrays are indexed. So to look at the 4th element of an array, you'd do:

Example 4-7. Accessing elements in an array

  string *colors = ({ "red", "blue", "green", "yellow", "black" });

  string fourth_color = colors[3];  // fourth_color here will be "yellow"

Remember that array indexes are 0-based. The first element is index 0, the second element is index 1, the third is index 2, the fourth is index 3.

LPC has a range operator "..". This allows you to access a range of an array. In Python, this is called a slice. Some languages call it a subarray.

Example 4-8. Using the range operator on arrays

  string *names = ({ "joe", "jeff", "jack", "harry" });
  string *somenames = names[0..2];

The variable somenames will be ({"joe", "jeff"}) since the range specifies index 0 up to index 2. Note that "up to" does not include the string at index 2.

The range also works for substrings since strings can be used as an array of characters:

  string bigname = "Jack the Ripper";
  string firstname = [0..strsrch(bigname, " ")];

You can also use indexes from the end of the string:

  string s = "Hello.";
  string s_with_no_period = s[0..<2];

String s will be "Hello." and s_with_no_period will be "Hello".