Array Object

class Array extends Object

An Array object contains a list or sequence of values.

Values are addressed by their position within the array (known as an array index), where position 1 is the first element.

Arrays are often created by enclosing a list of values in brackets. For example:

veg := ["Asparagus", "Broccoli", "Cucumber"]
Loop veg.Length
    MsgBox veg[A_Index]

A negative index can be used to address elements in reverse, so -1 is the last element, -2 is the second last element, and so on.

Attempting to use an array index which is out of bounds (such as zero, or if its absolute value is greater than the Length of the array) is considered an error and will cause an IndexError to be thrown. The best way to add new elements to the array is to call InsertAt or Push. For example:

users := Array()
users.Push(A_UserName)
MsgBox users[1]

An array can also be extended by assigning a larger value to Length. This changes which indices are valid, but Has will show that the new elements have no value. Elements without a value are typically used for variadic calls or by variadic functions, but can be used for any purpose.

"ArrayObj" is used below as a placeholder for any Array object, as "Array" is the class itself.

In addition to the methods and properties inherited from Object, Array objects have the following predefined methods and properties.

Table of Contents

Static Methods

Call

Creates a new Array containing the specified values.

ArrayObj := Array(Value, Value2, ..., ValueN)
ArrayObj := Array.Call(Value, Value2, ..., ValueN)

Parameters are defined by __New.

Methods

Add

Appends one value and returns the new length.

Length := ArrayObj.Add(Value)

This avoids the variadic-call overhead of Push when only one value is added.

Clone

Returns a shallow copy of an array.

Clone := ArrayObj.Clone()

All array elements are copied to the new array. Object references are copied (like with a normal assignment), not the objects themselves.

Own properties, own methods and base are copied as per Obj.Clone.

Contains

Returns whether the array contains a value.

Boolean := ArrayObj.Contains(Value)

The return value is 1 (true) if an element equal to Value is present, otherwise 0 (false).

If Value is omitted, the search is for an element which has no value, as left behind by Delete.

Delete

Removes the value of an array element, leaving the index without a value.

RemovedValue := ArrayObj.Delete(Index)

Parameters

Index

Type: Integer

A valid array index.

Return Value

Type: Any

This method returns the removed value (blank-unset if none).

Remarks

This method does not affect the Length of the array.

A ValueError is thrown if Index is out of range.

Get

Returns the value at a given index, or a default value.

Value := ArrayObj.Get(Index , Default)

This method carries out the following steps:

  1. Throw an IndexError if Index is zero or out of range.
  2. Return the value at Index, if there is one (see Has).
  3. Return the value of the Default parameter, if specified.
  4. Return the value of ArrayObj.Default, if defined.
  5. [v2.1-alpha.29+]: If the caller is in v2.1 mode, return unset.
  6. Throw an UnsetItemError.

When Default is omitted, this is equivalent to ArrayObj[Index], except that __Item is not called.

Has

Returns a non-zero number if the index is valid and there is a value at that position.

HasIndex := ArrayObj.Has(Index)

InsertAt

Inserts one or more values at a given position.

ArrayObj.InsertAt(Index, Value1 , Value2, ... ValueN)

Parameters

Index

Type: Integer

The position to insert Value1 at. Subsequent values are inserted at Index+1, Index+2, etc. Specifying an index of 0 is the same as specifying Length + 1.

Value1 ...

Type: Any

One or more values to insert. To insert an array of values, pass theArray* as the last parameter.

Remarks

InsertAt is the counterpart of RemoveAt.

Any items previously at or to the right of Index are shifted to the right. Missing parameters are also inserted, but without a value. For example:

x := []
x.InsertAt(1, "A", "B") ; =>  ["A", "B"]
x.InsertAt(2, "C")      ; =>  ["A", "C", "B"]

; Missing elements are preserved:
x := ["A", , "C"]
x.InsertAt(2, "B")      ; =>  ["A", "B",    , "C"]

x := ["C"]
x.InsertAt(1, , "B")    ; =>  [   , "B", "C"]

A ValueError is thrown if Index is less than -ArrayObj.Length or greater than ArrayObj.Length + 1. For example, with an array of 3 items, Index must be between -3 and 4, inclusive.

Pop

Removes and returns the last array element.

RemovedValue := ArrayObj.Pop()

All of the following are equivalent:

RemovedValue := ArrayObj.Pop()
RemovedValue := ArrayObj.RemoveAt(ArrayObj.Length)
RemovedValue := ArrayObj.RemoveAt(-1)

If the array is empty (Length is 0), an Error is thrown.

If the last item has a value, it is returned. Otherwise the return value is blank-unset.

Push

Appends values to the end of an array.

ArrayObj.Push(Value, Value2, ..., ValueN)

Parameters

Value ...

Type: Any

One or more values to insert. To insert an array of values, pass theArray* as the last parameter.

RemoveAt

Removes items from an array.

RemovedValue := ArrayObj.RemoveAt(Index)
ArrayObj.RemoveAt(Index, Length)

Parameters

Index

Type: Integer

The index of the value or values to remove.

Length

Type: Integer

If omitted, one item is removed. Otherwise, specify the length of the range of values to remove.

Return Value

Type: Any

If Length is omitted and the item has a value, it is returned. Otherwise the return value is blank-unset.

Remarks

RemoveAt is the counterpart of InsertAt.

A ValueError is thrown if the range indicated by Index and Length is not entirely within the array's current bounds.

The remaining items to the right of Pos are shifted to the left by Length (or 1 if omitted). For example:

x := ["A", "B"]
MsgBox x.RemoveAt(1)  ; A
MsgBox x[1]           ; B

x := ["A", , "C"]
MsgBox x.RemoveAt(1, 2)  ; 1
MsgBox x[1]              ; C

Remove

Removes the first occurrence of a value.

Boolean := ArrayObj.Remove(Value)

Elements after the removed value are shifted to the left. If the value is not present, the array is unchanged.

If Value is omitted, the first element which has no value is removed, as left behind by Delete.

The return value is 1 (true) if an element equal to Value was found and removed, otherwise 0 (false).

Filter

Returns a new Array containing each element for which a callback returned true.

Filtered := ArrayObj.Filter(Callback , StartIndex := 1)

The callback receives (Value, Index); it may declare only the parameters it needs.

A negative StartIndex begins at the corresponding position from the end and filters toward the beginning, so the result is in reverse order.

FindIndex

Returns the index of the first element for which a callback returns true, or 0 if none does.

Index := ArrayObj.FindIndex(Callback , StartIndex := 1)

A negative StartIndex begins at the corresponding position from the end and searches toward the beginning.

IndexOf

Returns the first index whose value equals Value, or 0 if it is absent.

Index := ArrayObj.IndexOf(Value, StartIndex := 1)

A negative StartIndex searches toward the beginning.

If Value is omitted, the search is for an element which has no value, as left behind by Delete.

An IndexError is thrown if StartIndex is 0 or its absolute value exceeds Length. Searching an empty array is not an error; the return value is 0.

Join

Returns the string representation of every element separated by Separator.

Text := ArrayObj.Join(Separator := ",")

MapTo

Returns a new Array containing the value returned by a callback for each source element from StartIndex.

Mapped := ArrayObj.MapTo(Callback , StartIndex := 1)

The callback receives (Value, Index).

arr := [10, 20, 30]
arr2 := arr.MapTo((x, i) => x * i)

MaxIndex / MinIndex

Returns the highest or lowest index. These compatibility methods are also available on Map.

Highest := ArrayObj.MaxIndex()
Lowest := ArrayObj.MinIndex()

Sort

Sorts the Array in place and returns the Array.

ArrayObj.Sort(Callback)

The callback receives two values and should return a negative number when the first belongs before the second, zero when equal, or a positive number otherwise.

ToString

Returns a string representation of the array.

Text := ArrayObj.ToString()

The result encloses the elements in square brackets and separates them with a comma and space. String elements are enclosed in double quotes, and elements without a value are represented by unset. String(ArrayObj) returns the same result.

__New

Appends items. Equivalent to Push.

ArrayObj.__New(Value, Value2, ..., ValueN)

This method exists to support Call, and is not intended to be called directly. See Construction and Destruction.

__Enum

Enumerates array elements.

For Value in ArrayObj
For Index, Value in ArrayObj

Returns a new enumerator. This method is typically not called directly. Instead, the array object is passed directly to a for-loop, which calls __Enum once and then calls the enumerator once for each iteration of the loop. Each call to the enumerator returns the next array element. The for-loop's variables correspond to the enumerator's parameters, which are:

Index

Type: Integer

The array index, typically the same as A_Index. This is present only in the two-parameter mode.

Value

Type: Any

The value (if there is no value, Value becomes unset).

Properties

Length

Gets or sets the length of an array.

Length := ArrayObj.Length
ArrayObj.Length := Length

The length includes elements which have no value. Increasing the length changes which indices are considered valid, but the new elements have no value (as indicated by Has). Decreasing the length truncates the array.

MsgBox ["A", "B", "C"].Length  ;  3
MsgBox ["A",    , "C"].Length  ;  3

Capacity

Gets or sets the current capacity of an array.

MaxItems := ArrayObj.Capacity
ArrayObj.Capacity := MaxItems

MaxItems is an integer representing the maximum number of elements the array should be able to contain before it must be automatically expanded. If setting a value less than Length, elements are removed.

Default

Sets the default value returned when an element with no value is requested.

ArrayObj.Default := Value

This property actually doesn't exist by default, but can be defined by the script. If defined, its value is returned by __Item or Get if the requested element has no value, instead of throwing an UnsetItemError or returning unset. It can be implemented by any of the normal means, including a dynamic property or meta-function, but determining which key was queried would require overriding __Item or Get instead.

Setting a default value does not prevent an error from being thrown when the index is out of range.

__Item

Gets or sets the value of an array element.

Value := ArrayObj[Index]
Value := ArrayObj.__Item[Index]
ArrayObj[Index] := Value
ArrayObj.__Item[Index] := Value

Index is an integer representing a valid array index; that is, an integer with absolute value between 1 and Length (inclusive). A negative index can be used to address elements in reverse, so that -1 is the last element, -2 is the second last element, and so on. Attempting to use an index which is out of bounds (such as zero, or if its absolute value is greater than the Length of the array) is considered an error and will cause an IndexError to be thrown.

The property name __Item is typically omitted, as shown above, but is used when overriding the property.

[v2.1-alpha.29+]: In v2.1 mode, the return value is unset if the array element has no value and Default is not defined. This may result in the caller throwing an UnsetError.