Skip to main content
An array is a list of values of one type that can grow and shrink while the script runs. Use one when you need to keep a varying number of values: the last N prices, the swing points found so far, the labels you have drawn. The array namespace holds the functions (see array); this page shows how they fit together.

Create an array

array.new<type>(size, initial) creates an array of size elements, each set to initial; both arguments are optional, so array.new<float>(0) is an empty list. The type in angle brackets may be any fundamental type (int, float, bool, string, color), a drawing type (label, line, box, linefill, polyline, table), chartPoint, or a type of your own.
array.new_float(0), array.new_int(...), array.new_label(...) and their siblings are the same as the angle-bracket form, except that array.new_bool(3) holds false where array.new<bool>(3) holds na; every other type holds na until set. To declare the type of a variable, write array<float>:

Add, read and remove

  • array.push(a, x) adds at the end; array.unshift(a, x) at the start.
  • array.get(a, i) reads the element at index i; the first element is index 0 and the last is array.length(a) - 1. An index outside that range, including a negative one, stops the script when it runs with an error from array.get.
  • array.set(a, i, x) replaces an element.
  • array.pop(a) removes and returns the last element; array.shift(a) the first.
  • array.length(a) is the number of elements. There is no array.size.
  • An array holds at most 10,000 elements; growing it past that stops the script when it runs.
The functions can also be called on the array itself: a.push(close) is array.push(a, close), and a.length() is array.length(a). A name the array namespace does not have is refused either way, for example a.size(): Could not find any type function size for a. a[1] is not the element at index 1: [] on an array is the history operator, so a[1] is the array as it was on the previous bar. Use array.get(a, 1) for an element.

Keep an array across bars

A plain declaration creates a new array on every bar. Declare it static to create it once and keep adding to it:

Loop over an array

for x in a visits each element in order; a must be an array variable, not an expression. Changing x inside the loop does not change the element: use array.set for that. Prefer for x in a to a counted loop over the indexes: a counted loop does not run its body when the start and the end are equal (see Loops), so for i = 0 to array.length(a) - 1 skips a one-element array.

Arrays of drawings

An array of drawings lets a script keep a fixed number of them and delete the oldest:
For arrays of your own types, see Custom types and enums.

Arrays are shared, not copied

Assigning an array to another name gives a second name for the same array: b = a and then array.set(b, 0, x) changes a too. array.copy(a) returns an independent array with the same elements.