The VScript Book

Chapter 1.2: Ordered Data - Arrays

An Array is a simple, ordered list, indexed by numbers starting from 0.

// An array of test chamber names
local chamberList = ["Chamber 01", "Chamber 02", "Chamber 03"]
printl(chamberList[0]) // Prints "Chamber 01"

Useful Array Methods

Arrays come with many built-in functions:

  • .len(): Returns the number of items in the array.
  • .append(value) or .push(value): Adds a new item to the very end of the array.
  • .extend(other_array): Appends all items from another array to the end of this one.
  • .pop(): Removes the last item from the array and returns it.
  • .top(): Returns the last item in the array without removing it.
  • .insert(index, value): Inserts a new item at a specific index, shifting subsequent items forward.
  • .remove(index): Removes the item at the specified index and shifts all following items down.
  • .clear(): Removes all items from the array, making it empty.
  • .resize(new_size, [fill_value]): Changes the array's size. If the new size is larger, new slots are filled with fill_value (or null if not provided).
  • .sort([compare_func]): Sorts the array in place. You can optionally provide a custom function to define the sort order.
  • .reverse(): Reverses the order of items in the array in place.
  • .slice(start_index, [end_index]): Creates a new, smaller array from a piece of the original. It copies from start_index up to (but not including) end_index.
  • .tostring(): Returns a default string representation of the array, like "(array : pointer)".

Looping Through Arrays: foreach

The easiest way to go through every item in an array is the foreach loop.

local panelSequence = ["up", "down", "down", "up"]

// 'idx' will be 0, 1, 2, 3
// 'direction' will be "up", "down", "down", "up"
foreach(idx, direction in panelSequence) {
    printl("Step " + idx + ": panel goes " + direction)
}

Arrays are Just Special Tables

Deep Dive: Under the hood, an Array in Squirrel is simply a Table where the keys are automatically assigned as integers (0, 1, 2, and so on). This is why you can access elements with myArray[0] and why they share some methods like .len(). Understanding this relationship helps demystify how Squirrel handles data.