List


Lists (or arrays) are simple sequence of objects, their size is dynamic and their index starts always from 0. They provide fast random access to their elements. You can create a list by placing a sequence of comma-separated expressions inside square brackets:


	var r = [1, 2, "Hello", 3.1415, true];
	
	// list has a count property
	var n = r.count;	// n is 5
			

Accessing elements

You can access an element from a list by calling the subscript operator [] on it with the index of the element you want. Like most languages, indexes start at zero:


	var names = ["Mark", "Andrew", "Paul", "Ross", "Frank", "Max"];
	names[0];	// "Mark"
	names[2];	// "Paul"
			

Negative indices counts backwards from the end:


	var names = ["Mark", "Andrew", "Paul", "Ross", "Frank", "Max"];
	names[-1];	// "Max"
	names[-2];	// "Frank"
			

Iterating elements

The subscript operator works well for finding values when you know the key you’re looking for, but sometimes you want to see everything that’s in the list. Since the List class implements the iterator method, you can easily use it in a for loop:


	var people = ["Mark", "Andrew", "Paul", "Ross", "Frank", "Max"];
	for (var name in people) {
		System.print("Current name is " + name);
	}
			

Adding elements

A List instance can be expanded by setting an index greater than current list size:


	var list = [10,20,30,40,50];
	list[30] = 22;	// list contains now 31 elements (index 0...30)
			

List as a stack

The List class implements the push/pop methods as a convenient way to threat a list as a stack:


	var list = [10,20,30,40,50];
	list.push(100);		// add 100 to the list
	var v1 = list.pop();	// pop 100
	var v2 = list.pop();	// pop 50