Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/doc/classes/Array.xml
11352 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]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.
41
</description>
42
<tutorials>
43
</tutorials>
44
<constructors>
45
<constructor name="Array">
46
<return type="Array" />
47
<description>
48
Constructs an empty [Array].
49
</description>
50
</constructor>
51
<constructor name="Array">
52
<return type="Array" />
53
<param index="0" name="base" type="Array" />
54
<param index="1" name="type" type="int" />
55
<param index="2" name="class_name" type="StringName" />
56
<param index="3" name="script" type="Variant" />
57
<description>
58
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:
59
- [param type] is the built-in [Variant] type, as one the [enum Variant.Type] constants.
60
- [param class_name] is the built-in class name (see [method Object.get_class]).
61
- [param script] is the associated script. It must be a [Script] instance or [code]null[/code].
62
If [param type] is not [constant TYPE_OBJECT], [param class_name] must be an empty [StringName] and [param script] must be [code]null[/code].
63
[codeblock]
64
class_name Sword
65
extends Node
66
67
class Stats:
68
pass
69
70
func _ready():
71
var a = Array([], TYPE_INT, "", null) # Array[int]
72
var b = Array([], TYPE_OBJECT, "Node", null) # Array[Node]
73
var c = Array([], TYPE_OBJECT, "Node", Sword) # Array[Sword]
74
var d = Array([], TYPE_OBJECT, "RefCounted", Stats) # Array[Stats]
75
[/codeblock]
76
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].
77
In GDScript, this constructor is usually not necessary, as it is possible to create a typed array through static typing:
78
[codeblock]
79
var numbers: Array[float] = []
80
var children: Array[Node] = [$Node, $Sprite2D, $RigidBody3D]
81
82
var integers: Array[int] = [0.2, 4.5, -2.0]
83
print(integers) # Prints [0, 4, -2]
84
[/codeblock]
85
</description>
86
</constructor>
87
<constructor name="Array">
88
<return type="Array" />
89
<param index="0" name="from" type="Array" />
90
<description>
91
Returns the same array as [param from]. If you need a copy of the array, use [method duplicate].
92
</description>
93
</constructor>
94
<constructor name="Array">
95
<return type="Array" />
96
<param index="0" name="from" type="PackedByteArray" />
97
<description>
98
Constructs an array from a [PackedByteArray].
99
</description>
100
</constructor>
101
<constructor name="Array">
102
<return type="Array" />
103
<param index="0" name="from" type="PackedColorArray" />
104
<description>
105
Constructs an array from a [PackedColorArray].
106
</description>
107
</constructor>
108
<constructor name="Array">
109
<return type="Array" />
110
<param index="0" name="from" type="PackedFloat32Array" />
111
<description>
112
Constructs an array from a [PackedFloat32Array].
113
</description>
114
</constructor>
115
<constructor name="Array">
116
<return type="Array" />
117
<param index="0" name="from" type="PackedFloat64Array" />
118
<description>
119
Constructs an array from a [PackedFloat64Array].
120
</description>
121
</constructor>
122
<constructor name="Array">
123
<return type="Array" />
124
<param index="0" name="from" type="PackedInt32Array" />
125
<description>
126
Constructs an array from a [PackedInt32Array].
127
</description>
128
</constructor>
129
<constructor name="Array">
130
<return type="Array" />
131
<param index="0" name="from" type="PackedInt64Array" />
132
<description>
133
Constructs an array from a [PackedInt64Array].
134
</description>
135
</constructor>
136
<constructor name="Array">
137
<return type="Array" />
138
<param index="0" name="from" type="PackedStringArray" />
139
<description>
140
Constructs an array from a [PackedStringArray].
141
</description>
142
</constructor>
143
<constructor name="Array">
144
<return type="Array" />
145
<param index="0" name="from" type="PackedVector2Array" />
146
<description>
147
Constructs an array from a [PackedVector2Array].
148
</description>
149
</constructor>
150
<constructor name="Array">
151
<return type="Array" />
152
<param index="0" name="from" type="PackedVector3Array" />
153
<description>
154
Constructs an array from a [PackedVector3Array].
155
</description>
156
</constructor>
157
<constructor name="Array">
158
<return type="Array" />
159
<param index="0" name="from" type="PackedVector4Array" />
160
<description>
161
Constructs an array from a [PackedVector4Array].
162
</description>
163
</constructor>
164
</constructors>
165
<methods>
166
<method name="all" qualifiers="const">
167
<return type="bool" />
168
<param index="0" name="method" type="Callable" />
169
<description>
170
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].
171
The [param method] should take one [Variant] parameter (the current array element) and return a [bool].
172
[codeblocks]
173
[gdscript]
174
func greater_than_5(number):
175
return number &gt; 5
176
177
func _ready():
178
print([6, 10, 6].all(greater_than_5)) # Prints true (3/3 elements evaluate to true).
179
print([4, 10, 4].all(greater_than_5)) # Prints false (1/3 elements evaluate to true).
180
print([4, 4, 4].all(greater_than_5)) # Prints false (0/3 elements evaluate to true).
181
print([].all(greater_than_5)) # Prints true (0/0 elements evaluate to true).
182
183
# Same as the first line above, but using a lambda function.
184
print([6, 10, 6].all(func(element): return element &gt; 5)) # Prints true
185
[/gdscript]
186
[csharp]
187
private static bool GreaterThan5(int number)
188
{
189
return number &gt; 5;
190
}
191
192
public override void _Ready()
193
{
194
// Prints True (3/3 elements evaluate to true).
195
GD.Print(new Godot.Collections.Array&gt;int&lt; { 6, 10, 6 }.All(GreaterThan5));
196
// Prints False (1/3 elements evaluate to true).
197
GD.Print(new Godot.Collections.Array&gt;int&lt; { 4, 10, 4 }.All(GreaterThan5));
198
// Prints False (0/3 elements evaluate to true).
199
GD.Print(new Godot.Collections.Array&gt;int&lt; { 4, 4, 4 }.All(GreaterThan5));
200
// Prints True (0/0 elements evaluate to true).
201
GD.Print(new Godot.Collections.Array&gt;int&lt; { }.All(GreaterThan5));
202
203
// Same as the first line above, but using a lambda function.
204
GD.Print(new Godot.Collections.Array&gt;int&lt; { 6, 10, 6 }.All(element =&gt; element &gt; 5)); // Prints True
205
}
206
[/csharp]
207
[/codeblocks]
208
See also [method any], [method filter], [method map] and [method reduce].
209
[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).
210
[b]Note:[/b] For an empty array, this method [url=https://en.wikipedia.org/wiki/Vacuous_truth]always[/url] returns [code]true[/code].
211
</description>
212
</method>
213
<method name="any" qualifiers="const">
214
<return type="bool" />
215
<param index="0" name="method" type="Callable" />
216
<description>
217
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].
218
The [param method] should take one [Variant] parameter (the current array element) and return a [bool].
219
[codeblock]
220
func greater_than_5(number):
221
return number &gt; 5
222
223
func _ready():
224
print([6, 10, 6].any(greater_than_5)) # Prints true (3 elements evaluate to true).
225
print([4, 10, 4].any(greater_than_5)) # Prints true (1 elements evaluate to true).
226
print([4, 4, 4].any(greater_than_5)) # Prints false (0 elements evaluate to true).
227
print([].any(greater_than_5)) # Prints false (0 elements evaluate to true).
228
229
# Same as the first line above, but using a lambda function.
230
print([6, 10, 6].any(func(number): return number &gt; 5)) # Prints true
231
[/codeblock]
232
See also [method all], [method filter], [method map] and [method reduce].
233
[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).
234
[b]Note:[/b] For an empty array, this method always returns [code]false[/code].
235
</description>
236
</method>
237
<method name="append">
238
<return type="void" />
239
<param index="0" name="value" type="Variant" />
240
<description>
241
Appends [param value] at the end of the array (alias of [method push_back]).
242
</description>
243
</method>
244
<method name="append_array">
245
<return type="void" />
246
<param index="0" name="array" type="Array" />
247
<description>
248
Appends another [param array] at the end of this array.
249
[codeblock]
250
var numbers = [1, 2, 3]
251
var extra = [4, 5, 6]
252
numbers.append_array(extra)
253
print(numbers) # Prints [1, 2, 3, 4, 5, 6]
254
[/codeblock]
255
</description>
256
</method>
257
<method name="assign">
258
<return type="void" />
259
<param index="0" name="array" type="Array" />
260
<description>
261
Assigns elements of another [param array] into the array. Resizes the array to match [param array]. Performs type conversions if the array is typed.
262
</description>
263
</method>
264
<method name="back" qualifiers="const">
265
<return type="Variant" />
266
<description>
267
Returns the last element of the array. If the array is empty, fails and returns [code]null[/code]. See also [method front].
268
[b]Note:[/b] Unlike with the [code][][/code] operator ([code]array[-1][/code]), an error is generated without stopping project execution.
269
</description>
270
</method>
271
<method name="bsearch" qualifiers="const">
272
<return type="int" />
273
<param index="0" name="value" type="Variant" />
274
<param index="1" name="before" type="bool" default="true" />
275
<description>
276
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].
277
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.
278
[codeblock]
279
var numbers = [2, 4, 8, 10]
280
var idx = numbers.bsearch(7)
281
282
numbers.insert(idx, 7)
283
print(numbers) # Prints [2, 4, 7, 8, 10]
284
285
var fruits = ["Apple", "Lemon", "Lemon", "Orange"]
286
print(fruits.bsearch("Lemon", true)) # Prints 1, points at the first "Lemon".
287
print(fruits.bsearch("Lemon", false)) # Prints 3, points at "Orange".
288
[/codeblock]
289
[b]Note:[/b] Calling [method bsearch] on an [i]unsorted[/i] array will result in unexpected behavior. Use [method sort] before calling this method.
290
</description>
291
</method>
292
<method name="bsearch_custom" qualifiers="const">
293
<return type="int" />
294
<param index="0" name="value" type="Variant" />
295
<param index="1" name="func" type="Callable" />
296
<param index="2" name="before" type="bool" default="true" />
297
<description>
298
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].
299
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].
300
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.
301
[codeblock]
302
func sort_by_amount(a, b):
303
if a[1] &lt; b[1]:
304
return true
305
return false
306
307
func _ready():
308
var my_items = [["Tomato", 2], ["Kiwi", 5], ["Rice", 9]]
309
310
var apple = ["Apple", 5]
311
# "Apple" is inserted before "Kiwi".
312
my_items.insert(my_items.bsearch_custom(apple, sort_by_amount, true), apple)
313
314
var banana = ["Banana", 5]
315
# "Banana" is inserted after "Kiwi".
316
my_items.insert(my_items.bsearch_custom(banana, sort_by_amount, false), banana)
317
318
# Prints [["Tomato", 2], ["Apple", 5], ["Kiwi", 5], ["Banana", 5], ["Rice", 9]]
319
print(my_items)
320
[/codeblock]
321
[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.
322
</description>
323
</method>
324
<method name="clear">
325
<return type="void" />
326
<description>
327
Removes all elements from the array. This is equivalent to using [method resize] with a size of [code]0[/code].
328
</description>
329
</method>
330
<method name="count" qualifiers="const">
331
<return type="int" />
332
<param index="0" name="value" type="Variant" />
333
<description>
334
Returns the number of times an element is in the array.
335
To count how many elements in an array satisfy a condition, see [method reduce].
336
</description>
337
</method>
338
<method name="duplicate" qualifiers="const">
339
<return type="Array" />
340
<param index="0" name="deep" type="bool" default="false" />
341
<description>
342
Returns a new copy of the array.
343
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.
344
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.
345
</description>
346
</method>
347
<method name="duplicate_deep" qualifiers="const">
348
<return type="Array" />
349
<param index="0" name="deep_subresources_mode" type="int" default="1" />
350
<description>
351
Duplicates this array, deeply, like [method duplicate][code](true)[/code], with extra control over how subresources are handled.
352
[param deep_subresources_mode] must be one of the values from [enum Resource.DeepDuplicateMode]. By default, only internal resources will be duplicated (recursively).
353
</description>
354
</method>
355
<method name="erase">
356
<return type="void" />
357
<param index="0" name="value" type="Variant" />
358
<description>
359
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.
360
[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.
361
[b]Note:[/b] Erasing elements while iterating over arrays is [b]not[/b] supported and will result in unpredictable behavior.
362
</description>
363
</method>
364
<method name="fill">
365
<return type="void" />
366
<param index="0" name="value" type="Variant" />
367
<description>
368
Assigns the given [param value] to all elements in the array.
369
This method can often be combined with [method resize] to create an array with a given size and initialized elements:
370
[codeblocks]
371
[gdscript]
372
var array = []
373
array.resize(5)
374
array.fill(2)
375
print(array) # Prints [2, 2, 2, 2, 2]
376
[/gdscript]
377
[csharp]
378
Godot.Collections.Array array = [];
379
array.Resize(5);
380
array.Fill(2);
381
GD.Print(array); // Prints [2, 2, 2, 2, 2]
382
[/csharp]
383
[/codeblocks]
384
[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.
385
</description>
386
</method>
387
<method name="filter" qualifiers="const">
388
<return type="Array" />
389
<param index="0" name="method" type="Callable" />
390
<description>
391
Calls the given [Callable] on each element in the array and returns a new, filtered [Array].
392
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.
393
[codeblock]
394
func is_even(number):
395
return number % 2 == 0
396
397
func _ready():
398
print([1, 4, 5, 8].filter(is_even)) # Prints [4, 8]
399
400
# Same as above, but using a lambda function.
401
print([1, 4, 5, 8].filter(func(number): return number % 2 == 0))
402
[/codeblock]
403
See also [method any], [method all], [method map] and [method reduce].
404
</description>
405
</method>
406
<method name="find" qualifiers="const">
407
<return type="int" />
408
<param index="0" name="what" type="Variant" />
409
<param index="1" name="from" type="int" default="0" />
410
<description>
411
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.
412
[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.
413
[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.
414
</description>
415
</method>
416
<method name="find_custom" qualifiers="const">
417
<return type="int" />
418
<param index="0" name="method" type="Callable" />
419
<param index="1" name="from" type="int" default="0" />
420
<description>
421
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.
422
[param method] is a callable that takes an element of the array, and returns a [bool].
423
[b]Note:[/b] If you just want to know whether the array contains [i]anything[/i] that satisfies [param method], use [method any].
424
[codeblocks]
425
[gdscript]
426
func is_even(number):
427
return number % 2 == 0
428
429
func _ready():
430
print([1, 3, 4, 7].find_custom(is_even.bind())) # Prints 2
431
[/gdscript]
432
[/codeblocks]
433
</description>
434
</method>
435
<method name="front" qualifiers="const">
436
<return type="Variant" />
437
<description>
438
Returns the first element of the array. If the array is empty, fails and returns [code]null[/code]. See also [method back].
439
[b]Note:[/b] Unlike with the [code][][/code] operator ([code]array[0][/code]), an error is generated without stopping project execution.
440
</description>
441
</method>
442
<method name="get" qualifiers="const">
443
<return type="Variant" />
444
<param index="0" name="index" type="int" />
445
<description>
446
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].
447
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.
448
</description>
449
</method>
450
<method name="get_typed_builtin" qualifiers="const">
451
<return type="int" />
452
<description>
453
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].
454
</description>
455
</method>
456
<method name="get_typed_class_name" qualifiers="const">
457
<return type="StringName" />
458
<description>
459
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].
460
</description>
461
</method>
462
<method name="get_typed_script" qualifiers="const">
463
<return type="Variant" />
464
<description>
465
Returns the [Script] instance associated with this typed array, or [code]null[/code] if it does not exist. See also [method is_typed].
466
</description>
467
</method>
468
<method name="has" qualifiers="const" keywords="includes, contains">
469
<return type="bool" />
470
<param index="0" name="value" type="Variant" />
471
<description>
472
Returns [code]true[/code] if the array contains the given [param value].
473
[codeblocks]
474
[gdscript]
475
print(["inside", 7].has("inside")) # Prints true
476
print(["inside", 7].has("outside")) # Prints false
477
print(["inside", 7].has(7)) # Prints true
478
print(["inside", 7].has("7")) # Prints false
479
[/gdscript]
480
[csharp]
481
Godot.Collections.Array arr = ["inside", 7];
482
// By C# convention, this method is renamed to `Contains`.
483
GD.Print(arr.Contains("inside")); // Prints True
484
GD.Print(arr.Contains("outside")); // Prints False
485
GD.Print(arr.Contains(7)); // Prints True
486
GD.Print(arr.Contains("7")); // Prints False
487
[/csharp]
488
[/codeblocks]
489
In GDScript, this is equivalent to the [code]in[/code] operator:
490
[codeblock]
491
if 4 in [2, 4, 6, 8]:
492
print("4 is here!") # Will be printed.
493
[/codeblock]
494
[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.
495
</description>
496
</method>
497
<method name="hash" qualifiers="const">
498
<return type="int" />
499
<description>
500
Returns a hashed 32-bit integer value representing the array and its contents.
501
[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.
502
</description>
503
</method>
504
<method name="insert">
505
<return type="int" />
506
<param index="0" name="position" type="int" />
507
<param index="1" name="value" type="Variant" />
508
<description>
509
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.
510
Returns [constant OK] on success, or one of the other [enum Error] constants if this method fails.
511
[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.
512
</description>
513
</method>
514
<method name="is_empty" qualifiers="const">
515
<return type="bool" />
516
<description>
517
Returns [code]true[/code] if the array is empty ([code][][/code]). See also [method size].
518
</description>
519
</method>
520
<method name="is_read_only" qualifiers="const">
521
<return type="bool" />
522
<description>
523
Returns [code]true[/code] if the array is read-only. See [method make_read_only].
524
In GDScript, arrays are automatically read-only if declared with the [code]const[/code] keyword.
525
</description>
526
</method>
527
<method name="is_same_typed" qualifiers="const">
528
<return type="bool" />
529
<param index="0" name="array" type="Array" />
530
<description>
531
Returns [code]true[/code] if this array is typed the same as the given [param array]. See also [method is_typed].
532
</description>
533
</method>
534
<method name="is_typed" qualifiers="const">
535
<return type="bool" />
536
<description>
537
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].
538
In GDScript, it is possible to define a typed array with static typing:
539
[codeblock]
540
var numbers: Array[float] = [0.2, 4.2, -2.0]
541
print(numbers.is_typed()) # Prints true
542
[/codeblock]
543
</description>
544
</method>
545
<method name="make_read_only">
546
<return type="void" />
547
<description>
548
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.
549
In GDScript, arrays are automatically read-only if declared with the [code]const[/code] keyword.
550
</description>
551
</method>
552
<method name="map" qualifiers="const">
553
<return type="Array" />
554
<param index="0" name="method" type="Callable" />
555
<description>
556
Calls the given [Callable] for each element in the array and returns a new array filled with values returned by the [param method].
557
The [param method] should take one [Variant] parameter (the current array element) and can return any [Variant].
558
[codeblock]
559
func double(number):
560
return number * 2
561
562
func _ready():
563
print([1, 2, 3].map(double)) # Prints [2, 4, 6]
564
565
# Same as above, but using a lambda function.
566
print([1, 2, 3].map(func(element): return element * 2))
567
[/codeblock]
568
See also [method filter], [method reduce], [method any] and [method all].
569
</description>
570
</method>
571
<method name="max" qualifiers="const">
572
<return type="Variant" />
573
<description>
574
Returns the maximum value contained in the array, if all elements can be compared. Otherwise, returns [code]null[/code]. See also [method min].
575
To find the maximum value using a custom comparator, you can use [method reduce].
576
</description>
577
</method>
578
<method name="min" qualifiers="const">
579
<return type="Variant" />
580
<description>
581
Returns the minimum value contained in the array, if all elements can be compared. Otherwise, returns [code]null[/code]. See also [method max].
582
</description>
583
</method>
584
<method name="pick_random" qualifiers="const">
585
<return type="Variant" />
586
<description>
587
Returns a random element from the array. Generates an error and returns [code]null[/code] if the array is empty.
588
[codeblocks]
589
[gdscript]
590
# May print 1, 2, 3.25, or "Hi".
591
print([1, 2, 3.25, "Hi"].pick_random())
592
[/gdscript]
593
[csharp]
594
Godot.Collections.Array array = [1, 2, 3.25f, "Hi"];
595
GD.Print(array.PickRandom()); // May print 1, 2, 3.25, or "Hi".
596
[/csharp]
597
[/codeblocks]
598
[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].
599
</description>
600
</method>
601
<method name="pop_at">
602
<return type="Variant" />
603
<param index="0" name="position" type="int" />
604
<description>
605
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.
606
[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.
607
</description>
608
</method>
609
<method name="pop_back">
610
<return type="Variant" />
611
<description>
612
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].
613
</description>
614
</method>
615
<method name="pop_front">
616
<return type="Variant" />
617
<description>
618
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].
619
[b]Note:[/b] This method shifts every other element's index back, which may have a noticeable performance cost, especially on larger arrays.
620
</description>
621
</method>
622
<method name="push_back">
623
<return type="void" />
624
<param index="0" name="value" type="Variant" />
625
<description>
626
Appends an element at the end of the array. See also [method push_front].
627
</description>
628
</method>
629
<method name="push_front">
630
<return type="void" />
631
<param index="0" name="value" type="Variant" />
632
<description>
633
Adds an element at the beginning of the array. See also [method push_back].
634
[b]Note:[/b] This method shifts every other element's index forward, which may have a noticeable performance cost, especially on larger arrays.
635
</description>
636
</method>
637
<method name="reduce" qualifiers="const">
638
<return type="Variant" />
639
<param index="0" name="method" type="Callable" />
640
<param index="1" name="accum" type="Variant" default="null" />
641
<description>
642
Calls the given [Callable] for each element in array, accumulates the result in [param accum], then returns it.
643
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].
644
[codeblock]
645
func sum(accum, number):
646
return accum + number
647
648
func _ready():
649
print([1, 2, 3].reduce(sum, 0)) # Prints 6
650
print([1, 2, 3].reduce(sum, 10)) # Prints 16
651
652
# Same as above, but using a lambda function.
653
print([1, 2, 3].reduce(func(accum, number): return accum + number, 10))
654
[/codeblock]
655
If [method max] is not desirable, this method may also be used to implement a custom comparator:
656
[codeblock]
657
func _ready():
658
var arr = [Vector2i(5, 0), Vector2i(3, 4), Vector2i(1, 2)]
659
660
var longest_vec = arr.reduce(func(max, vec): return vec if is_length_greater(vec, max) else max)
661
print(longest_vec) # Prints (3, 4)
662
663
func is_length_greater(a, b):
664
return a.length() &gt; b.length()
665
[/codeblock]
666
This method can also be used to count how many elements in an array satisfy a certain condition, similar to [method count]:
667
[codeblock]
668
func is_even(number):
669
return number % 2 == 0
670
671
func _ready():
672
var arr = [1, 2, 3, 4, 5]
673
# If the current element is even, increment count, otherwise leave count the same.
674
var even_count = arr.reduce(func(count, next): return count + 1 if is_even(next) else count, 0)
675
print(even_count) # Prints 2
676
[/codeblock]
677
See also [method map], [method filter], [method any], and [method all].
678
</description>
679
</method>
680
<method name="remove_at">
681
<return type="void" />
682
<param index="0" name="position" type="int" />
683
<description>
684
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.
685
If you need to return the removed element, use [method pop_at]. To remove an element by value, use [method erase] instead.
686
[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.
687
[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].
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