Work in progress
Godot documentation is being updated to reflect the latest changes in version
4.0
. Some documentation pages may
still state outdated information. This banner will tell you if you're reading one of such pages.
The contents of this page are up to date. If you can still find outdated information, please open an issue.
Array¶
A generic array datatype.
Description¶
A generic array that can contain several elements of any type, accessible by a numerical index starting at 0. Negative indices can be used to count from the back, like in Python (-1 is the last element, -2 is the second to last, etc.).
Example:
var array = ["One", 2, 3, "Four"]
print(array[0]) # One.
print(array[2]) # 3.
print(array[-1]) # Four.
array[2] = "Three"
print(array[-2]) # Three.
var array = new Godot.Collections.Array{"One", 2, 3, "Four"};
GD.Print(array[0]); // One.
GD.Print(array[2]); // 3.
GD.Print(array[array.Count - 1]); // Four.
array[2] = "Three";
GD.Print(array[array.Count - 2]); // Three.
Arrays can be concatenated using the +
operator:
var array1 = ["One", 2]
var array2 = [3, "Four"]
print(array1 + array2) # ["One", 2, 3, "Four"]
// Array concatenation is not possible with C# arrays, but is with Godot.Collections.Array.
var array1 = new Godot.Collections.Array{"One", 2};
var array2 = new Godot.Collections.Array{3, "Four"};
GD.Print(array1 + array2); // Prints [One, 2, 3, Four]
Note: Concatenating with the +=
operator will create a new array, which has a cost. If you want to append another array to an existing array, append_array is more efficient.
Note: Arrays are always passed by reference. To get a copy of an array that can be modified independently of the original array, use duplicate.
Note: Erasing elements while iterating over arrays is not supported and will result in unpredictable behavior.
Note: When declaring an array with const
, the array itself can still be mutated by defining the values at individual indices or pushing/removing elements. Using const
will only prevent assigning the constant with another value after it was initialized.
Constructors¶
Array ( ) |
|
Array ( Array base, int type, StringName class_name, Variant script ) |
|
Array ( PackedByteArray from ) |
|
Array ( PackedColorArray from ) |
|
Array ( PackedFloat32Array from ) |
|
Array ( PackedFloat64Array from ) |
|
Array ( PackedInt32Array from ) |
|
Array ( PackedInt64Array from ) |
|
Array ( PackedStringArray from ) |
|
Array ( PackedVector2Array from ) |
|
Array ( PackedVector3Array from ) |
Methods¶
void |
|
void |
append_array ( Array array ) |
void |
|
back ( ) const |
|
bsearch_custom ( Variant value, Callable func, bool before=true ) const |
|
void |
clear ( ) |
void |
|
void |
|
front ( ) const |
|
get_typed_builtin ( ) const |
|
get_typed_class_name ( ) const |
|
get_typed_script ( ) const |
|
hash ( ) const |
|
is_empty ( ) const |
|
is_read_only ( ) const |
|
is_same_typed ( Array array ) const |
|
is_typed ( ) const |
|
void |
make_read_only ( ) |
max ( ) const |
|
min ( ) const |
|
pick_random ( ) const |
|
pop_back ( ) |
|
pop_front ( ) |
|
void |
|
void |
push_front ( Variant value ) |
void |
|
void |
reverse ( ) |
void |
shuffle ( ) |
size ( ) const |
|
slice ( int begin, int end=2147483647, int step=1, bool deep=false ) const |
|
void |
sort ( ) |
void |
sort_custom ( Callable func ) |
Operators¶
operator != ( Array right ) |
|
operator + ( Array right ) |
|
operator < ( Array right ) |
|
operator <= ( Array right ) |
|
operator == ( Array right ) |
|
operator > ( Array right ) |
|
operator >= ( Array right ) |
|
operator [] ( int index ) |
Constructor Descriptions¶
Array Array ( )
Constructs an empty Array.
Array Array ( Array base, int type, StringName class_name, Variant script )
Creates a typed array from the base
array.
Returns the same array as from
. If you need a copy of the array, use duplicate.
Array Array ( PackedByteArray from )
Constructs an array from a PackedByteArray.
Array Array ( PackedColorArray from )
Constructs an array from a PackedColorArray.
Array Array ( PackedFloat32Array from )
Constructs an array from a PackedFloat32Array.
Array Array ( PackedFloat64Array from )
Constructs an array from a PackedFloat64Array.
Array Array ( PackedInt32Array from )
Constructs an array from a PackedInt32Array.
Array Array ( PackedInt64Array from )
Constructs an array from a PackedInt64Array.
Array Array ( PackedStringArray from )
Constructs an array from a PackedStringArray.
Array Array ( PackedVector2Array from )
Constructs an array from a PackedVector2Array.
Array Array ( PackedVector3Array from )
Constructs an array from a PackedVector3Array.
Method Descriptions¶
bool all ( Callable method ) const
Calls the provided Callable on each element in the array and returns true
if the Callable returns true
for all elements in the array. If the Callable returns false
for one array element or more, this method returns false
.
The callable's method should take one Variant parameter (the current array element) and return a boolean value.
func _ready():
print([6, 10, 6].all(greater_than_5)) # Prints True (3/3 elements evaluate to `true`).
print([4, 10, 4].all(greater_than_5)) # Prints False (1/3 elements evaluate to `true`).
print([4, 4, 4].all(greater_than_5)) # Prints False (0/3 elements evaluate to `true`).
print([].all(greater_than_5)) # Prints True (0/0 elements evaluate to `true`).
print([6, 10, 6].all(func(number): return number > 5)) # Prints True. Same as the first line above, but using lambda function.
func greater_than_5(number):
return number > 5
See also any, filter, map and reduce.
Note: Unlike relying on the size of an array returned by filter, this method will return as early as possible to improve performance (especially with large arrays).
Note: For an empty array, this method always returns true
.
bool any ( Callable method ) const
Calls the provided Callable on each element in the array and returns true
if the Callable returns true
for one or more elements in the array. If the Callable returns false
for all elements in the array, this method returns false
.
The callable's method should take one Variant parameter (the current array element) and return a boolean value.
func _ready():
print([6, 10, 6].any(greater_than_5)) # Prints True (3 elements evaluate to `true`).
print([4, 10, 4].any(greater_than_5)) # Prints True (1 elements evaluate to `true`).
print([4, 4, 4].any(greater_than_5)) # Prints False (0 elements evaluate to `true`).
print([].any(greater_than_5)) # Prints False (0 elements evaluate to `true`).
print([6, 10, 6].any(func(number): return number > 5)) # Prints True. Same as the first line above, but using lambda function.
func greater_than_5(number):
return number > 5
See also all, filter, map and reduce.
Note: Unlike relying on the size of an array returned by filter, this method will return as early as possible to improve performance (especially with large arrays).
Note: For an empty array, this method always returns false
.
void append ( Variant value )
Appends an element at the end of the array (alias of push_back).
void append_array ( Array array )
Appends another array at the end of this array.
var array1 = [1, 2, 3]
var array2 = [4, 5, 6]
array1.append_array(array2)
print(array1) # Prints [1, 2, 3, 4, 5, 6].
void assign ( Array array )
Assigns elements of another array
into the array. Resizes the array to match array
. Performs type conversions if the array is typed.
Variant back ( ) const
Returns the last element of the array. Prints an error and returns null
if the array is empty.
Note: Calling this function is not the same as writing array[-1]
. If the array is empty, accessing by index will pause project execution when running from the editor.
int bsearch ( Variant value, bool before=true ) const
Finds the index of an existing value (or the insertion index that maintains sorting order, if the value is not yet present in the array) using binary search. Optionally, a before
specifier can be passed. If false
, the returned index comes after all existing entries of the value in the array.
Note: Calling bsearch on an unsorted array results in unexpected behavior.
int bsearch_custom ( Variant value, Callable func, bool before=true ) const
Finds the index of an existing value (or the insertion index that maintains sorting order, if the value is not yet present in the array) using binary search and a custom comparison method. Optionally, a before
specifier can be passed. If false
, the returned index comes after all existing entries of the value in the array. The custom method receives two arguments (an element from the array and the value searched for) and must return true
if the first argument is less than the second, and return false
otherwise.
Note: Calling bsearch_custom on an unsorted array results in unexpected behavior.
void clear ( )
Clears the array. This is equivalent to using resize with a size of 0
.
int count ( Variant value ) const
Returns the number of times an element is in the array.
Array duplicate ( bool deep=false ) const
Returns a copy of the array.
If deep
is true
, a deep copy is performed: all nested arrays and dictionaries are duplicated and will not be shared with the original array. If false
, a shallow copy is made and references to the original nested arrays and dictionaries are kept, so that modifying a sub-array or dictionary in the copy will also impact those referenced in the source array. Note that any Object-derived elements will be shallow copied regardless of the deep
setting.
void erase ( Variant value )
Removes the first occurrence of a value from the array. If the value does not exist in the array, nothing happens. To remove an element by index, use remove_at instead.
Note: This method acts in-place and doesn't return a value.
Note: On large arrays, this method will be slower if the removed element is close to the beginning of the array (index 0). This is because all elements placed after the removed element have to be reindexed.
Note: Do not erase entries while iterating over the array.
void fill ( Variant value )
Assigns the given value to all elements in the array. This can typically be used together with resize to create an array with a given size and initialized elements:
var array = []
array.resize(10)
array.fill(0) # Initialize the 10 elements to 0.
var array = new Godot.Collections.Array();
array.Resize(10);
array.Fill(0); // Initialize the 10 elements to 0.
Note: If value
is of a reference type (Object-derived, Array, Dictionary, etc.) then the array is filled with the references to the same object, i.e. no duplicates are created.
Array filter ( Callable method ) const
Calls the provided Callable on each element in the array and returns a new array with the elements for which the method returned true
.
The callable's method should take one Variant parameter (the current array element) and return a boolean value.
func _ready():
print([1, 2, 3].filter(remove_1)) # Prints [2, 3].
print([1, 2, 3].filter(func(number): return number != 1)) # Same as above, but using lambda function.
func remove_1(number):
return number != 1
See also any, all, map and reduce.
int find ( Variant what, int from=0 ) const
Searches the array for a value and returns its index or -1
if not found. Optionally, the initial search index can be passed.
Variant front ( ) const
Returns the first element of the array. Prints an error and returns null
if the array is empty.
Note: Calling this function is not the same as writing array[0]
. If the array is empty, accessing by index will pause project execution when running from the editor.
int get_typed_builtin ( ) const
Returns the Variant.Type constant for a typed array. If the Array is not typed, returns @GlobalScope.TYPE_NIL.
StringName get_typed_class_name ( ) const
Returns a class name of a typed Array of type @GlobalScope.TYPE_OBJECT.
Variant get_typed_script ( ) const
Returns the script associated with a typed array tied to a class name.
bool has ( Variant value ) const
Returns true
if the array contains the given value.
print(["inside", 7].has("inside")) # True
print(["inside", 7].has("outside")) # False
print(["inside", 7].has(7)) # True
print(["inside", 7].has("7")) # False
var arr = new Godot.Collections.Array { "inside", 7 };
// has is renamed to Contains
GD.Print(arr.Contains("inside")); // True
GD.Print(arr.Contains("outside")); // False
GD.Print(arr.Contains(7)); // True
GD.Print(arr.Contains("7")); // False
Note: This is equivalent to using the in
operator as follows:
# Will evaluate to `true`.
if 2 in [2, 4, 6, 8]:
print("Contains!")
// As there is no "in" keyword in C#, you have to use Contains
var array = new Godot.Collections.Array { 2, 4, 6, 8 };
if (array.Contains(2))
{
GD.Print("Contains!");
}
int hash ( ) const
Returns a hashed 32-bit integer value representing the array and its contents.
Note: Arrays with equal content will always produce identical hash values. However, the reverse is not true. Returning identical hash values does not imply the arrays are equal, because different arrays can have identical hash values due to hash collisions.
int insert ( int position, Variant value )
Inserts a new element at a given position in the array. The position must be valid, or at the end of the array (pos == size()
).
Note: This method acts in-place and doesn't return a value.
Note: On large arrays, this method will be slower if the inserted element is close to the beginning of the array (index 0). This is because all elements placed after the newly inserted element have to be reindexed.
bool is_empty ( ) const
Returns true
if the array is empty.
bool is_read_only ( ) const
Returns true
if the array is read-only. See make_read_only. Arrays are automatically read-only if declared with const
keyword.
bool is_same_typed ( Array array ) const
Returns true
if the array is typed the same as array
.
bool is_typed ( ) const
Returns true
if the array is typed. Typed arrays can only store elements of their associated type and provide type safety for the []
operator. Methods of typed array still return Variant.
void make_read_only ( )
Makes the array read-only, i.e. disabled modifying of the array's elements. Does not apply to nested content, e.g. content of nested arrays.
Array map ( Callable method ) const
Calls the provided Callable for each element in the array and returns a new array filled with values returned by the method.
The callable's method should take one Variant parameter (the current array element) and can return any Variant.
func _ready():
print([1, 2, 3].map(negate)) # Prints [-1, -2, -3].
print([1, 2, 3].map(func(number): return -number)) # Same as above, but using lambda function.
func negate(number):
return -number
See also filter, reduce, any and all.
Variant max ( ) const
Returns the maximum value contained in the array if all elements are of comparable types. If the elements can't be compared, null
is returned.
Variant min ( ) const
Returns the minimum value contained in the array if all elements are of comparable types. If the elements can't be compared, null
is returned.
Variant pick_random ( ) const
Returns a random value from the target array.
var array: Array[int] = [1, 2, 3, 4]
print(array.pick_random()) # Prints either of the four numbers.
var array = new Godot.Collections.Array { 1, 2, 3, 4 };
GD.Print(array.PickRandom()); // Prints either of the four numbers.
Variant pop_at ( int position )
Removes and returns the element of the array at index position
. If negative, position
is considered relative to the end of the array. Leaves the array untouched and returns null
if the array is empty or if it's accessed out of bounds. An error message is printed when the array is accessed out of bounds, but not when the array is empty.
Note: On large arrays, this method can be slower than pop_back as it will reindex the array's elements that are located after the removed element. The larger the array and the lower the index of the removed element, the slower pop_at will be.
Variant pop_back ( )
Removes and returns the last element of the array. Returns null
if the array is empty, without printing an error message. See also pop_front.
Variant pop_front ( )
Re