Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/doc/classes/Array.xml
20920 views
1
<?xml version="1.0" encoding="UTF-8" ?>
2
<class name="Array" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
3
<brief_description>
4
A built-in data structure that holds a sequence of elements.
5
</brief_description>
6
<description>
7
An array data structure that can contain a sequence of elements of any [Variant] type by default. Values can optionally be constrained to a specific type by creating a [i]typed array[/i]. Elements are accessed by a numerical index starting at [code]0[/code]. Negative indices are used to count from the back ([code]-1[/code] is the last element, [code]-2[/code] is the second to last, etc.).
8
[codeblocks]
9
[gdscript]
10
var array = ["First", 2, 3, "Last"]
11
print(array[0]) # Prints "First"
12
print(array[2]) # Prints 3
13
print(array[-1]) # Prints "Last"
14
15
array[1] = "Second"
16
print(array[1]) # Prints "Second"
17
print(array[-3]) # Prints "Second"
18
19
# This typed array can only contain integers.
20
# Attempting to add any other type will result in an error.
21
var typed_array: Array[int] = [1, 2, 3]
22
[/gdscript]
23
[csharp]
24
Godot.Collections.Array array = ["First", 2, 3, "Last"];
25
GD.Print(array[0]); // Prints "First"
26
GD.Print(array[2]); // Prints 3
27
GD.Print(array[^1]); // Prints "Last"
28
29
array[1] = "Second";
30
GD.Print(array[1]); // Prints "Second"
31
GD.Print(array[^3]); // Prints "Second"
32
33
// This typed array can only contain integers.
34
// Attempting to add any other type will result in an error.
35
Godot.Collections.Array&lt;int&gt; typedArray = [1, 2, 3];
36
[/csharp]
37
[/codeblocks]
38
[b]Note:[/b] Arrays are always passed by [b]reference[/b]. To get a copy of an array that can be modified independently of the original array, use [method duplicate].
39
[b]Note:[/b] Erasing elements while iterating over arrays is [b]not[/b] supported and will result in unpredictable behavior.
40
[b]Note:[/b] In a boolean context, an array will evaluate to [code]false[/code] if it's empty ([code][][/code]). Otherwise, an array will always evaluate to [code]true[/code].
41
[b]Differences between packed arrays, typed arrays, and untyped arrays:[/b] Packed arrays are generally faster to iterate on and modify compared to a typed array of the same type (e.g. [PackedInt64Array] versus [code]Array[int][/code]). Also, packed arrays consume less memory. As a downside, packed arrays are less flexible as they don't offer as many convenience methods such as [method Array.map]. Typed arrays are in turn faster to iterate on and modify than untyped arrays.
42
</description>
43
<tutorials>
44
</tutorials>
45
<constructors>
46
<constructor name="Array">
47
<return type="Array" />
48
<description>
49
Constructs an empty [Array].
50
</description>
51
</constructor>
52
<constructor name="Array">
53
<return type="Array" />
54
<param index="0" name="base" type="Array" />
55
<param index="1" name="type" type="int" />
56
<param index="2" name="class_name" type="StringName" />
57
<param index="3" name="script" type="Variant" />
58
<description>
59
Creates a typed array from the [param base] array. A typed array can only contain elements of the given type, or that inherit from the given class, as described by this constructor's parameters:
60
- [param type] is the built-in [Variant] type, as one the [enum Variant.Type] constants.
61
- [param class_name] is the built-in class name (see [method Object.get_class]).
62
- [param script] is the associated script. It must be a [Script] instance or [code]null[/code].
63
If [param type] is not [constant TYPE_OBJECT], [param class_name] must be an empty [StringName] and [param script] must be [code]null[/code].
64
[codeblock]
65
class_name Sword
66
extends Node
67
68
class Stats:
69
pass
70
71
func _ready():
72
var a = Array([], TYPE_INT, "", null) # Array[int]
73
var b = Array([], TYPE_OBJECT, "Node", null) # Array[Node]
74
var c = Array([], TYPE_OBJECT, "Node", Sword) # Array[Sword]
75
var d = Array([], TYPE_OBJECT, "RefCounted", Stats) # Array[Stats]
76
[/codeblock]
77
The [param base] array's elements are converted when necessary. If this is not possible or [param base] is already typed, this constructor fails and returns an empty [Array].
78
In GDScript, this constructor is usually not necessary, as it is possible to create a typed array through static typing:
79
[codeblock]
80
var numbers: Array[float] = []
81
var children: Array[Node] = [$Node, $Sprite2D, $RigidBody3D]
82
83
var integers: Array[int] = [0.2, 4.5, -2.0]
84
print(integers) # Prints [0, 4, -2]
85
[/codeblock]
86
</description>
87
</constructor>
88
<constructor name="Array">
89
<return type="Array" />
90
<param index="0" name="from" type="Array" />
91
<description>
92
Returns the same array as [param from]. If you need a copy of the array, use [method duplicate].
93
</description>
94
</constructor>
95
<constructor name="Array">
96
<return type="Array" />
97
<param index="0" name="from" type="PackedByteArray" />
98
<description>
99
Constructs an array from a [PackedByteArray].
100
</description>
101
</constructor>
102
<constructor name="Array">
103
<return type="Array" />
104
<param index="0" name="from" type="PackedColorArray" />
105
<description>
106
Constructs an array from a [PackedColorArray].
107
</description>
108
</constructor>
109
<constructor name="Array">
110
<return type="Array" />
111
<param index="0" name="from" type="PackedFloat32Array" />
112
<description>
113
Constructs an array from a [PackedFloat32Array].
114
</description>
115
</constructor>
116
<constructor name="Array">
117
<return type="Array" />
118
<param index="0" name="from" type="PackedFloat64Array" />
119
<description>
120
Constructs an array from a [PackedFloat64Array].
121
</description>
122
</constructor>
123
<constructor name="Array">
124
<return type="Array" />
125
<param index="0" name="from" type="PackedInt32Array" />
126
<description>
127
Constructs an array from a [PackedInt32Array].
128
</description>
129
</constructor>
130
<constructor name="Array">
131
<return type="Array" />
132
<param index="0" name="from" type="PackedInt64Array" />
133
<description>
134
Constructs an array from a [PackedInt64Array].
135
</description>
136
</constructor>
137
<constructor name="Array">
138
<return type="Array" />
139
<param index="0" name="from" type="PackedStringArray" />
140
<description>
141
Constructs an array from a [PackedStringArray].
142
</description>
143
</constructor>
144
<constructor name="Array">
145
<return type="Array" />
146
<param index="0" name="from" type="PackedVector2Array" />
147
<description>
148
Constructs an array from a [PackedVector2Array].
149
</description>
150
</constructor>
151
<constructor name="Array">
152
<return type="Array" />
153
<param index="0" name="from" type="PackedVector3Array" />
154
<description>
155
Constructs an array from a [PackedVector3Array].
156
</description>
157
</constructor>
158
<constructor name="Array">
159
<return type="Array" />
160
<param index="0" name="from" type="PackedVector4Array" />
161
<description>
162
Constructs an array from a [PackedVector4Array].
163
</description>
164
</constructor>
165
</constructors>
166
<methods>
167
<method name="all" qualifiers="const">
168
<return type="bool" />
169
<param index="0" name="method" type="Callable" />
170
<description>
171
Calls the given [Callable] on each element in the array and returns [code]true[/code] if the [Callable] returns [code]true[/code] for [i]all[/i] elements in the array. If the [Callable] returns [code]false[/code] for one array element or more, this method returns [code]false[/code].
172
The [param method] should take one [Variant] parameter (the current array element) and return a [bool].
173
[codeblocks]
174
[gdscript]
175
func greater_than_5(number):
176
return number &gt; 5
177
178
func _ready():
179
print([6, 10, 6].all(greater_than_5)) # Prints true (3/3 elements evaluate to true).
180
print([4, 10, 4].all(greater_than_5)) # Prints false (1/3 elements evaluate to true).
181
print([4, 4, 4].all(greater_than_5)) # Prints false (0/3 elements evaluate to true).
182
print([].all(greater_than_5)) # Prints true (0/0 elements evaluate to true).
183
184
# Same as the first line above, but using a lambda function.
185
print([6, 10, 6].all(func(element): return element &gt; 5)) # Prints true
186
[/gdscript]
187
[csharp]
188
private static bool GreaterThan5(int number)
189
{
190
return number &gt; 5;
191
}
192
193
public override void _Ready()
194
{
195
// Prints True (3/3 elements evaluate to true).
196
GD.Print(new Godot.Collections.Array&gt;int&lt; { 6, 10, 6 }.All(GreaterThan5));
197
// Prints False (1/3 elements evaluate to true).
198
GD.Print(new Godot.Collections.Array&gt;int&lt; { 4, 10, 4 }.All(GreaterThan5));
199
// Prints False (0/3 elements evaluate to true).
200
GD.Print(new Godot.Collections.Array&gt;int&lt; { 4, 4, 4 }.All(GreaterThan5));
201
// Prints True (0/0 elements evaluate to true).
202
GD.Print(new Godot.Collections.Array&gt;int&lt; { }.All(GreaterThan5));
203
204
// Same as the first line above, but using a lambda function.
205
GD.Print(new Godot.Collections.Array&gt;int&lt; { 6, 10, 6 }.All(element =&gt; element &gt; 5)); // Prints True
206
}
207
[/csharp]
208
[/codeblocks]
209
See also [method any], [method filter], [method map] and [method reduce].
210
[b]Note:[/b] Unlike relying on the size of an array returned by [method filter], this method will return as early as possible to improve performance (especially with large arrays).
211
[b]Note:[/b] For an empty array, this method [url=https://en.wikipedia.org/wiki/Vacuous_truth]always[/url] returns [code]true[/code].
212
</description>
213
</method>
214
<method name="any" qualifiers="const">
215
<return type="bool" />
216
<param index="0" name="method" type="Callable" />
217
<description>
218
Calls the given [Callable] on each element in the array and returns [code]true[/code] if the [Callable] returns [code]true[/code] for [i]one or more[/i] elements in the array. If the [Callable] returns [code]false[/code] for all elements in the array, this method returns [code]false[/code].
219
The [param method] should take one [Variant] parameter (the current array element) and return a [bool].
220
[codeblock]
221
func greater_than_5(number):
222
return number &gt; 5
223
224
func _ready():
225
print([6, 10, 6].any(greater_than_5)) # Prints true (3 elements evaluate to true).
226
print([4, 10, 4].any(greater_than_5)) # Prints true (1 elements evaluate to true).
227
print([4, 4, 4].any(greater_than_5)) # Prints false (0 elements evaluate to true).
228
print([].any(greater_than_5)) # Prints false (0 elements evaluate to true).
229
230
# Same as the first line above, but using a lambda function.
231
print([6, 10, 6].any(func(number): return number &gt; 5)) # Prints true
232
[/codeblock]
233
See also [method all], [method filter], [method map] and [method reduce].
234
[b]Note:[/b] Unlike relying on the size of an array returned by [method filter], this method will return as early as possible to improve performance (especially with large arrays).
235
[b]Note:[/b] For an empty array, this method always returns [code]false[/code].
236
</description>
237
</method>
238
<method name="append">
239
<return type="void" />
240
<param index="0" name="value" type="Variant" />
241
<description>
242
Appends [param value] at the end of the array (alias of [method push_back]).
243
</description>
244
</method>
245
<method name="append_array">
246
<return type="void" />
247
<param index="0" name="array" type="Array" />
248
<description>
249
Appends another [param array] at the end of this array.
250
[codeblock]
251
var numbers = [1, 2, 3]
252
var extra = [4, 5, 6]
253
numbers.append_array(extra)
254
print(numbers) # Prints [1, 2, 3, 4, 5, 6]
255
[/codeblock]
256
</description>
257
</method>
258
<method name="assign">
259
<return type="void" />
260
<param index="0" name="array" type="Array" />
261
<description>
262
Assigns elements of another [param array] into the array. Resizes the array to match [param array]. Performs type conversions if the array is typed.
263
</description>
264
</method>
265
<method name="back" qualifiers="const">
266
<return type="Variant" />
267
<description>
268
Returns the last element of the array. If the array is empty, fails and returns [code]null[/code]. See also [method front].
269
[b]Note:[/b] Unlike with the [code][][/code] operator ([code]array[-1][/code]), an error is generated without stopping project execution.
270
</description>
271
</method>
272
<method name="bsearch" qualifiers="const">
273
<return type="int" />
274
<param index="0" name="value" type="Variant" />
275
<param index="1" name="before" type="bool" default="true" />
276
<description>
277
Returns the index of [param value] in the sorted array. If it cannot be found, returns where [param value] should be inserted to keep the array sorted. The algorithm used is [url=https://en.wikipedia.org/wiki/Binary_search_algorithm]binary search[/url].
278
If [param before] is [code]true[/code] (as by default), the returned index comes before all existing elements equal to [param value] in the array.
279
[codeblock]
280
var numbers = [2, 4, 8, 10]
281
var idx = numbers.bsearch(7)
282
283
numbers.insert(idx, 7)
284
print(numbers) # Prints [2, 4, 7, 8, 10]
285
286
var fruits = ["Apple", "Lemon", "Lemon", "Orange"]
287
print(fruits.bsearch("Lemon", true)) # Prints 1, points at the first "Lemon".
288
print(fruits.bsearch("Lemon", false)) # Prints 3, points at "Orange".
289
[/codeblock]
290
[b]Note:[/b] Calling [method bsearch] on an [i]unsorted[/i] array will result in unexpected behavior. Use [method sort] before calling this method.
291
</description>
292
</method>
293
<method name="bsearch_custom" qualifiers="const">
294
<return type="int" />
295
<param index="0" name="value" type="Variant" />
296
<param index="1" name="func" type="Callable" />
297
<param index="2" name="before" type="bool" default="true" />
298
<description>
299
Returns the index of [param value] in the sorted array. If it cannot be found, returns where [param value] should be inserted to keep the array sorted (using [param func] for the comparisons). The algorithm used is [url=https://en.wikipedia.org/wiki/Binary_search_algorithm]binary search[/url].
300
Similar to [method sort_custom], [param func] is called as many times as necessary, receiving one array element and [param value] as arguments. The function should return [code]true[/code] if the array element should be [i]behind[/i] [param value], otherwise it should return [code]false[/code].
301
If [param before] is [code]true[/code] (as by default), the returned index comes before all existing elements equal to [param value] in the array.
302
[codeblock]
303
func sort_by_amount(a, b):
304
if a[1] &lt; b[1]:
305
return true
306
return false
307
308
func _ready():
309
var my_items = [["Tomato", 2], ["Kiwi", 5], ["Rice", 9]]
310
311
var apple = ["Apple", 5]
312
# "Apple" is inserted before "Kiwi".
313
my_items.insert(my_items.bsearch_custom(apple, sort_by_amount, true), apple)
314
315
var banana = ["Banana", 5]
316
# "Banana" is inserted after "Kiwi".
317
my_items.insert(my_items.bsearch_custom(banana, sort_by_amount, false), banana)
318
319
# Prints [["Tomato", 2], ["Apple", 5], ["Kiwi", 5], ["Banana", 5], ["Rice", 9]]
320
print(my_items)
321
[/codeblock]
322
[b]Note:[/b] Calling [method bsearch_custom] on an [i]unsorted[/i] array will result in unexpected behavior. Use [method sort_custom] with [param func] before calling this method.
323
</description>
324
</method>
325
<method name="clear">
326
<return type="void" />
327
<description>
328
Removes all elements from the array. This is equivalent to using [method resize] with a size of [code]0[/code].
329
</description>
330
</method>
331
<method name="count" qualifiers="const">
332
<return type="int" />
333
<param index="0" name="value" type="Variant" />
334
<description>
335
Returns the number of times an element is in the array.
336
To count how many elements in an array satisfy a condition, see [method reduce].
337
</description>
338
</method>
339
<method name="duplicate" qualifiers="const">
340
<return type="Array" />
341
<param index="0" name="deep" type="bool" default="false" />
342
<description>
343
Returns a new copy of the array.
344
By default, a [b]shallow[/b] copy is returned: all nested [Array], [Dictionary], and [Resource] elements are shared with the original array. Modifying any of those in one array will also affect them in the other.
345
If [param deep] is [code]true[/code], a [b]deep[/b] copy is returned: all nested arrays and dictionaries are also duplicated (recursively). Any [Resource] is still shared with the original array, though.
346
</description>
347
</method>
348
<method name="duplicate_deep" qualifiers="const">
349
<return type="Array" />
350
<param index="0" name="deep_subresources_mode" type="int" default="1" />
351
<description>
352
Duplicates this array, deeply, like [method duplicate] when passing [code]true[/code], with extra control over how subresources are handled.
353
[param deep_subresources_mode] must be one of the values from [enum Resource.DeepDuplicateMode]. By default, only internal resources will be duplicated (recursively).
354
</description>
355
</method>
356
<method name="erase">
357
<return type="void" />
358
<param index="0" name="value" type="Variant" />
359
<description>
360
Finds and removes the first occurrence of [param value] from the array. If [param value] does not exist in the array, nothing happens. To remove an element by index, use [method remove_at] instead.
361
[b]Note:[/b] This method shifts every element's index after the removed [param value] back, which may have a noticeable performance cost, especially on larger arrays.
362
[b]Note:[/b] Erasing elements while iterating over arrays is [b]not[/b] supported and will result in unpredictable behavior.
363
</description>
364
</method>
365
<method name="fill">
366
<return type="void" />
367
<param index="0" name="value" type="Variant" />
368
<description>
369
Assigns the given [param value] to all elements in the array.
370
This method can often be combined with [method resize] to create an array with a given size and initialized elements:
371
[codeblocks]
372
[gdscript]
373
var array = []
374
array.resize(5)
375
array.fill(2)
376
print(array) # Prints [2, 2, 2, 2, 2]
377
[/gdscript]
378
[csharp]
379
Godot.Collections.Array array = [];
380
array.Resize(5);
381
array.Fill(2);
382
GD.Print(array); // Prints [2, 2, 2, 2, 2]
383
[/csharp]
384
[/codeblocks]
385
[b]Note:[/b] If [param value] is a [Variant] passed by reference ([Object]-derived, [Array], [Dictionary], etc.), the array will be filled with references to the same [param value], which are not duplicates.
386
</description>
387
</method>
388
<method name="filter" qualifiers="const">
389
<return type="Array" />
390
<param index="0" name="method" type="Callable" />
391
<description>
392
Calls the given [Callable] on each element in the array and returns a new, filtered [Array].
393
The [param method] receives one of the array elements as an argument, and should return [code]true[/code] to add the element to the filtered array, or [code]false[/code] to exclude it.
394
[codeblock]
395
func is_even(number):
396
return number % 2 == 0
397
398
func _ready():
399
print([1, 4, 5, 8].filter(is_even)) # Prints [4, 8]
400
401
# Same as above, but using a lambda function.
402
print([1, 4, 5, 8].filter(func(number): return number % 2 == 0))
403
[/codeblock]
404
See also [method any], [method all], [method map] and [method reduce].
405
</description>
406
</method>
407
<method name="find" qualifiers="const">
408
<return type="int" />
409
<param index="0" name="what" type="Variant" />
410
<param index="1" name="from" type="int" default="0" />
411
<description>
412
Returns the index of the [b]first[/b] occurrence of [param what] in this array, or [code]-1[/code] if there are none. The search's start can be specified with [param from], continuing to the end of the array.
413
[b]Note:[/b] If you just want to know whether the array contains [param what], use [method has] ([code]Contains[/code] in C#). In GDScript, you may also use the [code]in[/code] operator.
414
[b]Note:[/b] For performance reasons, the search is affected by [param what]'s [enum Variant.Type]. For example, [code]7[/code] ([int]) and [code]7.0[/code] ([float]) are not considered equal for this method.
415
</description>
416
</method>
417
<method name="find_custom" qualifiers="const">
418
<return type="int" />
419
<param index="0" name="method" type="Callable" />
420
<param index="1" name="from" type="int" default="0" />
421
<description>
422
Returns the index of the [b]first[/b] element in the array that causes [param method] to return [code]true[/code], or [code]-1[/code] if there are none. The search's start can be specified with [param from], continuing to the end of the array.
423
[param method] is a callable that takes an element of the array, and returns a [bool].
424
[b]Note:[/b] If you just want to know whether the array contains [i]anything[/i] that satisfies [param method], use [method any].
425
[codeblocks]
426
[gdscript]
427
func is_even(number):
428
return number % 2 == 0
429
430
func _ready():
431
print([1, 3, 4, 7].find_custom(is_even.bind())) # Prints 2
432
[/gdscript]
433
[/codeblocks]
434
</description>
435
</method>
436
<method name="front" qualifiers="const">
437
<return type="Variant" />
438
<description>
439
Returns the first element of the array. If the array is empty, fails and returns [code]null[/code]. See also [method back].
440
[b]Note:[/b] Unlike with the [code][][/code] operator ([code]array[0][/code]), an error is generated without stopping project execution.
441
</description>
442
</method>
443
<method name="get" qualifiers="const">
444
<return type="Variant" />
445
<param index="0" name="index" type="int" />
446
<description>
447
Returns the element at the given [param index] in the array. If [param index] is out-of-bounds or negative, this method fails and returns [code]null[/code].
448
This method is similar (but not identical) to the [code][][/code] operator. Most notably, when this method fails, it doesn't pause project execution if run from the editor.
449
</description>
450
</method>
451
<method name="get_typed_builtin" qualifiers="const">
452
<return type="int" />
453
<description>
454
Returns the built-in [Variant] type of the typed array as a [enum Variant.Type] constant. If the array is not typed, returns [constant TYPE_NIL]. See also [method is_typed].
455
</description>
456
</method>
457
<method name="get_typed_class_name" qualifiers="const">
458
<return type="StringName" />
459
<description>
460
Returns the [b]built-in[/b] class name of the typed array, if the built-in [Variant] type [constant TYPE_OBJECT]. Otherwise, returns an empty [StringName]. See also [method is_typed] and [method Object.get_class].
461
</description>
462
</method>
463
<method name="get_typed_script" qualifiers="const">
464
<return type="Variant" />
465
<description>
466
Returns the [Script] instance associated with this typed array, or [code]null[/code] if it does not exist. See also [method is_typed].
467
</description>
468
</method>
469
<method name="has" qualifiers="const" keywords="includes, contains">
470
<return type="bool" />
471
<param index="0" name="value" type="Variant" />
472
<description>
473
Returns [code]true[/code] if the array contains the given [param value].
474
[codeblocks]
475
[gdscript]
476
print(["inside", 7].has("inside")) # Prints true
477
print(["inside", 7].has("outside")) # Prints false
478
print(["inside", 7].has(7)) # Prints true
479
print(["inside", 7].has("7")) # Prints false
480
[/gdscript]
481
[csharp]
482
Godot.Collections.Array arr = ["inside", 7];
483
// By C# convention, this method is renamed to `Contains`.
484
GD.Print(arr.Contains("inside")); // Prints True
485
GD.Print(arr.Contains("outside")); // Prints False
486
GD.Print(arr.Contains(7)); // Prints True
487
GD.Print(arr.Contains("7")); // Prints False
488
[/csharp]
489
[/codeblocks]
490
In GDScript, this is equivalent to the [code]in[/code] operator:
491
[codeblock]
492
if 4 in [2, 4, 6, 8]:
493
print("4 is here!") # Will be printed.
494
[/codeblock]
495
[b]Note:[/b] For performance reasons, the search is affected by the [param value]'s [enum Variant.Type]. For example, [code]7[/code] ([int]) and [code]7.0[/code] ([float]) are not considered equal for this method.
496
</description>
497
</method>
498
<method name="hash" qualifiers="const">
499
<return type="int" />
500
<description>
501
Returns a hashed 32-bit integer value representing the array and its contents.
502
[b]Note:[/b] Arrays with equal hash values are [i]not[/i] guaranteed to be the same, as a result of hash collisions. On the contrary, arrays with different hash values are guaranteed to be different.
503
</description>
504
</method>
505
<method name="insert">
506
<return type="int" />
507
<param index="0" name="position" type="int" />
508
<param index="1" name="value" type="Variant" />
509
<description>
510
Inserts a new element ([param value]) at a given index ([param position]) in the array. [param position] should be between [code]0[/code] and the array's [method size]. If negative, [param position] is considered relative to the end of the array.
511
Returns [constant OK] on success, or one of the other [enum Error] constants if this method fails.
512
[b]Note:[/b] Every element's index after [param position] needs to be shifted forward, which may have a noticeable performance cost, especially on larger arrays.
513
</description>
514
</method>
515
<method name="is_empty" qualifiers="const">
516
<return type="bool" />
517
<description>
518
Returns [code]true[/code] if the array is empty ([code][][/code]). See also [method size].
519
</description>
520
</method>
521
<method name="is_read_only" qualifiers="const">
522
<return type="bool" />
523
<description>
524
Returns [code]true[/code] if the array is read-only. See [method make_read_only].
525
In GDScript, arrays are automatically read-only if declared with the [code]const[/code] keyword.
526
</description>
527
</method>
528
<method name="is_same_typed" qualifiers="const">
529
<return type="bool" />
530
<param index="0" name="array" type="Array" />
531
<description>
532
Returns [code]true[/code] if this array is typed the same as the given [param array]. See also [method is_typed].
533
</description>
534
</method>
535
<method name="is_typed" qualifiers="const">
536
<return type="bool" />
537
<description>
538
Returns [code]true[/code] if the array is typed. Typed arrays can only contain elements of a specific type, as defined by the typed array constructor. The methods of a typed array are still expected to return a generic [Variant].
539
In GDScript, it is possible to define a typed array with static typing:
540
[codeblock]
541
var numbers: Array[float] = [0.2, 4.2, -2.0]
542
print(numbers.is_typed()) # Prints true
543
[/codeblock]
544
</description>
545
</method>
546
<method name="make_read_only">
547
<return type="void" />
548
<description>
549
Makes the array read-only. The array's elements cannot be overridden with different values, and their order cannot change. Does not apply to nested elements, such as dictionaries.
550
In GDScript, arrays are automatically read-only if declared with the [code]const[/code] keyword.
551
</description>
552
</method>
553
<method name="map" qualifiers="const">
554
<return type="Array" />
555
<param index="0" name="method" type="Callable" />
556
<description>
557
Calls the given [Callable] for each element in the array and returns a new array filled with values returned by the [param method].
558
The [param method] should take one [Variant] parameter (the current array element) and can return any [Variant].
559
[codeblock]
560
func double(number):
561
return number * 2
562
563
func _ready():
564
print([1, 2, 3].map(double)) # Prints [2, 4, 6]
565
566
# Same as above, but using a lambda function.
567
print([1, 2, 3].map(func(element): return element * 2))
568
[/codeblock]
569
See also [method filter], [method reduce], [method any] and [method all].
570
</description>
571
</method>
572
<method name="max" qualifiers="const">
573
<return type="Variant" />
574
<description>
575
Returns the maximum value contained in the array, if all elements can be compared. Otherwise, returns [code]null[/code]. See also [method min].
576
To find the maximum value using a custom comparator, you can use [method reduce].
577
</description>
578
</method>
579
<method name="min" qualifiers="const">
580
<return type="Variant" />
581
<description>
582
Returns the minimum value contained in the array, if all elements can be compared. Otherwise, returns [code]null[/code]. See also [method max].
583
</description>
584
</method>
585
<method name="pick_random" qualifiers="const">
586
<return type="Variant" />
587
<description>
588
Returns a random element from the array. Generates an error and returns [code]null[/code] if the array is empty.
589
[codeblocks]
590
[gdscript]
591
# May print 1, 2, 3.25, or "Hi".
592
print([1, 2, 3.25, "Hi"].pick_random())
593
[/gdscript]
594
[csharp]
595
Godot.Collections.Array array = [1, 2, 3.25f, "Hi"];
596
GD.Print(array.PickRandom()); // May print 1, 2, 3.25, or "Hi".
597
[/csharp]
598
[/codeblocks]
599
[b]Note:[/b] Like many similar functions in the engine (such as [method @GlobalScope.randi] or [method shuffle]), this method uses a common, global random seed. To get a predictable outcome from this method, see [method @GlobalScope.seed].
600
</description>
601
</method>
602
<method name="pop_at">
603
<return type="Variant" />
604
<param index="0" name="position" type="int" />
605
<description>
606
Removes and returns the element of the array at index [param position]. If negative, [param position] is considered relative to the end of the array. Returns [code]null[/code] if the array is empty. If [param position] is out of bounds, an error message is also generated.
607
[b]Note:[/b] This method shifts every element's index after [param position] back, which may have a noticeable performance cost, especially on larger arrays.
608
</description>
609
</method>
610
<method name="pop_back">
611
<return type="Variant" />
612
<description>
613
Removes and returns the last element of the array. Returns [code]null[/code] if the array is empty, without generating an error. See also [method pop_front].
614
</description>
615
</method>
616
<method name="pop_front">
617
<return type="Variant" />
618
<description>
619
Removes and returns the first element of the array. Returns [code]null[/code] if the array is empty, without generating an error. See also [method pop_back].
620
[b]Note:[/b] This method shifts every other element's index back, which may have a noticeable performance cost, especially on larger arrays.
621
</description>
622
</method>
623
<method name="push_back">
624
<return type="void" />
625
<param index="0" name="value" type="Variant" />
626
<description>
627
Appends an element at the end of the array. See also [method push_front].
628
</description>
629
</method>
630
<method name="push_front">
631
<return type="void" />
632
<param index="0" name="value" type="Variant" />
633
<description>
634
Adds an element at the beginning of the array. See also [method push_back].
635
[b]Note:[/b] This method shifts every other element's index forward, which may have a noticeable performance cost, especially on larger arrays.
636
</description>
637
</method>
638
<method name="reduce" qualifiers="const">
639
<return type="Variant" />
640
<param index="0" name="method" type="Callable" />
641
<param index="1" name="accum" type="Variant" default="null" />
642
<description>
643
Calls the given [Callable] for each element in array, accumulates the result in [param accum], then returns it.
644
The [param method] takes two arguments: the current value of [param accum] and the current array element. If [param accum] is [code]null[/code] (as by default), the iteration will start from the second element, with the first one used as initial value of [param accum].
645
[codeblock]
646
func sum(accum, number):
647
return accum + number
648
649
func _ready():
650
print([1, 2, 3].reduce(sum, 0)) # Prints 6
651
print([1, 2, 3].reduce(sum, 10)) # Prints 16
652
653
# Same as above, but using a lambda function.
654
print([1, 2, 3].reduce(func(accum, number): return accum + number, 10))
655
[/codeblock]
656
If [method max] is not desirable, this method may also be used to implement a custom comparator:
657
[codeblock]
658
func _ready():
659
var arr = [Vector2i(5, 0), Vector2i(3, 4), Vector2i(1, 2)]
660
661
var longest_vec = arr.reduce(func(max, vec): return vec if is_length_greater(vec, max) else max)
662
print(longest_vec) # Prints (3, 4)
663
664
func is_length_greater(a, b):
665
return a.length() &gt; b.length()
666
[/codeblock]
667
This method can also be used to count how many elements in an array satisfy a certain condition, similar to [method count]:
668
[codeblock]
669
func is_even(number):
670
return number % 2 == 0
671
672
func _ready():
673
var arr = [1, 2, 3, 4, 5]
674
# If the current element is even, increment count, otherwise leave count the same.
675
var even_count = arr.reduce(func(count, next): return count + 1 if is_even(next) else count, 0)
676
print(even_count) # Prints 2
677
[/codeblock]
678
See also [method map], [method filter], [method any], and [method all].
679
</description>
680
</method>
681
<method name="remove_at">
682
<return type="void" />
683
<param index="0" name="position" type="int" />
684
<description>
685
Removes the element from the array at the given index ([param position]). If the index is out of bounds, this method fails. If the index is negative, [param position] is considered relative to the end of the array.
686
If you need to return the removed element, use [method pop_at]. To remove an element by value, use [method erase] instead.
687
[b]Note:[/b] This method shifts every element's index after [param position] back, which may have a noticeable performance cost, especially on larger arrays.
688
</description>
689
</method>
690
<method name="resize">
691
<return type="int" />
692
<param index="0" name="size" type="int" />
693
<description>
694
Sets the array's number of elements to [param size]. If [param size] is smaller than the array's current size, the elements at the end are removed. If [param size] is greater, new default elements (usually [code]null[/code]) are added, depending on the array's type.
695
Returns [constant OK] on success, or one of the following [enum Error] constants if this method fails: [constant ERR_LOCKED] if the array is read-only, [constant ERR_INVALID_PARAMETER] if the size is negative, or [constant ERR_OUT_OF_MEMORY] if allocations fail. Use [method size] to find the actual size of the array after resize.
696
[b]Note:[/b] Calling this method once and assigning the new values is faster than calling [method append] for every new element.
697
</description>
698
</method>
699
<method name="reverse">
700
<return type="void" />
701
<description>
702
Reverses the order of all elements in the array.
703
</description>
704
</method>
705
<method name="rfind" qualifiers="const">
706
<return type="int" />
707
<param index="0" name="what" type="Variant" />
708
<param index="1" name="from" type="int" default="-1" />
709
<description>
710
Returns the index of the [b]last[/b] occurrence of [param what] in this array, or [code]-1[/code] if there are none. The search's start can be specified with [param from], continuing to the beginning of the array. This method is the reverse of [method find].
711
</description>
712
</method>
713
<method name="rfind_custom" qualifiers="const">
714
<return type="int" />
715
<param index="0" name="method" type="Callable" />
716
<param index="1" name="from" type="int" default="-1" />
717
<description>
718
Returns the index of the [b]last[/b] element of the array that causes [param method] to return [code]true[/code], or [code]-1[/code] if there are none. The search's start can be specified with [param from], continuing to the beginning of the array. This method is the reverse of [method find_custom].
719
</description>
720
</method>
721
<method name="set">
722
<return type="void" />
723
<param index="0" name="index" type="int" />
724
<param index="1" name="value" type="Variant" />
725
<description>
726
Sets the value of the element at the given [param index] to the given [param value]. This will not change the size of the array, it only changes the value at an index already in the array. This is the same as using the [code][][/code] operator ([code]array[index] = value[/code]).
727
</description>
728
</method>
729
<method name="shuffle">
730
<return type="void" />
731
<description>
732
Shuffles all elements of the array in a random order.
733
[b]Note:[/b] Like many similar functions in the engine (such as [method @GlobalScope.randi] or [method pick_random]), this method uses a common, global random seed. To get a predictable outcome from this method, see [method @GlobalScope.seed].
734
</description>
735
</method>
736
<method name="size" qualifiers="const">
737
<return type="int" />
738
<description>
739
Returns the number of elements in the array. Empty arrays ([code][][/code]) always return [code]0[/code]. See also [method is_empty].
740
</description>
741
</method>
742
<method name="slice" qualifiers="const">
743
<return type="Array" />
744
<param index="0" name="begin" type="int" />
745
<param index="1" name="end" type="int" default="2147483647" />
746
<param index="2" name="step" type="int" default="1" />
747
<param index="3" name="deep" type="bool" default="false" />
748
<description>
749
Returns a new [Array] containing this array's elements, from index [param begin] (inclusive) to [param end] (exclusive), every [param step] elements.
750
If either [param begin] or [param end] are negative, their value is relative to the end of the array.
751
If [param step] is negative, this method iterates through the array in reverse, returning a slice ordered backwards. For this to work, [param begin] must be greater than [param end].
752
If [param deep] is [code]true[/code], all nested [Array] and [Dictionary] elements in the slice are duplicated from the original, recursively. See also [method duplicate].
753
[codeblock]
754
var letters = ["A", "B", "C", "D", "E", "F"]
755
756
print(letters.slice(0, 2)) # Prints ["A", "B"]
757
print(letters.slice(2, -2)) # Prints ["C", "D"]
758
print(letters.slice(-2, 6)) # Prints ["E", "F"]
759
760
print(letters.slice(0, 6, 2)) # Prints ["A", "C", "E"]
761
print(letters.slice(4, 1, -1)) # Prints ["E", "D", "C"]
762
[/codeblock]
763
</description>
764
</method>
765
<method name="sort">
766
<return type="void" />
767
<description>
768
Sorts the array in ascending order. The final order is dependent on the "less than" ([code]&lt;[/code]) comparison between elements.
769
[codeblocks]
770
[gdscript]
771
var numbers = [10, 5, 2.5, 8]
772
numbers.sort()
773
print(numbers) # Prints [2.5, 5, 8, 10]
774
[/gdscript]
775
[csharp]
776
Godot.Collections.Array numbers = [10, 5, 2.5, 8];
777
numbers.Sort();
778
GD.Print(numbers); // Prints [2.5, 5, 8, 10]
779
[/csharp]
780
[/codeblocks]
781
[b]Note:[/b] The sorting algorithm used is not [url=https://en.wikipedia.org/wiki/Sorting_algorithm#Stability]stable[/url]. This means that equivalent elements (such as [code]2[/code] and [code]2.0[/code]) may have their order changed when calling [method sort].
782
</description>
783
</method>
784
<method name="sort_custom">
785
<return type="void" />
786
<param index="0" name="func" type="Callable" />
787
<description>
788
Sorts the array using a custom [Callable].
789
[param func] is called as many times as necessary, receiving two array elements as arguments. The function should return [code]true[/code] if the first element should be moved [i]before[/i] the second one, otherwise it should return [code]false[/code].
790
[codeblock]
791
func sort_ascending(a, b):
792
if a[1] &lt; b[1]:
793
return true
794
return false
795
796
func _ready():
797
var my_items = [["Tomato", 5], ["Apple", 9], ["Rice", 4]]
798
my_items.sort_custom(sort_ascending)
799
print(my_items) # Prints [["Rice", 4], ["Tomato", 5], ["Apple", 9]]
800
801
# Sort descending, using a lambda function.
802
my_items.sort_custom(func(a, b): return a[1] &gt; b[1])
803
print(my_items) # Prints [["Apple", 9], ["Tomato", 5], ["Rice", 4]]
804
[/codeblock]
805
It may also be necessary to use this method to sort strings by natural order, with [method String.naturalnocasecmp_to], as in the following example:
806
[codeblock]
807
var files = ["newfile1", "newfile2", "newfile10", "newfile11"]
808
files.sort_custom(func(a, b): return a.naturalnocasecmp_to(b) &lt; 0)
809
print(files) # Prints ["newfile1", "newfile2", "newfile10", "newfile11"]
810
[/codeblock]
811
[b]Note:[/b] In C#, this method is not supported.
812
[b]Note:[/b] The sorting algorithm used is not [url=https://en.wikipedia.org/wiki/Sorting_algorithm#Stability]stable[/url]. This means that values considered equal may have their order changed when calling this method.
813
[b]Note:[/b] You should not randomize the return value of [param func], as the heapsort algorithm expects a consistent result. Randomizing the return value will result in unexpected behavior.
814
</description>
815
</method>
816
</methods>
817
<operators>
818
<operator name="operator !=">
819
<return type="bool" />
820
<param index="0" name="right" type="Array" />
821
<description>
822
Returns [code]true[/code] if the array's size or its elements are different than [param right]'s.
823
</description>
824
</operator>
825
<operator name="operator +">
826
<return type="Array" />
827
<param index="0" name="right" type="Array" />
828
<description>
829
Appends the [param right] array to the left operand, creating a new [Array]. This is also known as an array concatenation.
830
[codeblocks]
831
[gdscript]
832
var array1 = ["One", 2]
833
var array2 = [3, "Four"]
834
print(array1 + array2) # Prints ["One", 2, 3, "Four"]
835
[/gdscript]
836
[csharp]
837
// Note that concatenation is not possible with C#'s native Array type.
838
Godot.Collections.Array array1 = ["One", 2];
839
Godot.Collections.Array array2 = [3, "Four"];
840
GD.Print(array1 + array2); // Prints ["One", 2, 3, "Four"]
841
[/csharp]
842
[/codeblocks]
843
[b]Note:[/b] For existing arrays, [method append_array] is much more efficient than concatenation and assignment with the [code]+=[/code] operator.
844
</description>
845
</operator>
846
<operator name="operator &lt;">
847
<return type="bool" />
848
<param index="0" name="right" type="Array" />
849
<description>
850
Compares the elements of both arrays in order, starting from index [code]0[/code] and ending on the last index in common between both arrays. For each pair of elements, returns [code]true[/code] if this array's element is less than [param right]'s, [code]false[/code] if this element is greater. Otherwise, continues to the next pair.
851
If all searched elements are equal, returns [code]true[/code] if this array's size is less than [param right]'s, otherwise returns [code]false[/code].
852
</description>
853
</operator>
854
<operator name="operator &lt;=">
855
<return type="bool" />
856
<param index="0" name="right" type="Array" />
857
<description>
858
Compares the elements of both arrays in order, starting from index [code]0[/code] and ending on the last index in common between both arrays. For each pair of elements, returns [code]true[/code] if this array's element is less than [param right]'s, [code]false[/code] if this element is greater. Otherwise, continues to the next pair.
859
If all searched elements are equal, returns [code]true[/code] if this array's size is less or equal to [param right]'s, otherwise returns [code]false[/code].
860
</description>
861
</operator>
862
<operator name="operator ==">
863
<return type="bool" />
864
<param index="0" name="right" type="Array" />
865
<description>
866
Compares the left operand [Array] against the [param right] [Array]. Returns [code]true[/code] if the sizes and contents of the arrays are equal, [code]false[/code] otherwise.
867
</description>
868
</operator>
869
<operator name="operator &gt;">
870
<return type="bool" />
871
<param index="0" name="right" type="Array" />
872
<description>
873
Compares the elements of both arrays in order, starting from index [code]0[/code] and ending on the last index in common between both arrays. For each pair of elements, returns [code]true[/code] if this array's element is greater than [param right]'s, [code]false[/code] if this element is less. Otherwise, continues to the next pair.
874
If all searched elements are equal, returns [code]true[/code] if this array's size is greater than [param right]'s, otherwise returns [code]false[/code].
875
</description>
876
</operator>
877
<operator name="operator &gt;=">
878
<return type="bool" />
879
<param index="0" name="right" type="Array" />
880
<description>
881
Compares the elements of both arrays in order, starting from index [code]0[/code] and ending on the last index in common between both arrays. For each pair of elements, returns [code]true[/code] if this array's element is greater than [param right]'s, [code]false[/code] if this element is less. Otherwise, continues to the next pair.
882
If all searched elements are equal, returns [code]true[/code] if this array's size is greater or equal to [param right]'s, otherwise returns [code]false[/code].
883
</description>
884
</operator>
885
<operator name="operator []">
886
<return type="Variant" />
887
<param index="0" name="index" type="int" />
888
<description>
889
Returns the [Variant] element at the specified [param index]. Arrays start at index 0. If [param index] is greater or equal to [code]0[/code], the element is fetched starting from the beginning of the array. If [param index] is a negative value, the element is fetched starting from the end. Accessing an array out-of-bounds will cause a run-time error, pausing the project execution if run from the editor.
890
</description>
891
</operator>
892
</operators>
893
</class>
894
895