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