Initialize an array of size n

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By gax
:warning: Old Version Published before Godot 3 was released.

In Python, you can initialize an array of size n in one line with

[0] * n

Is there a similar feature for Godot?

:bust_in_silhouette: Reply From: kidscancode

No, but you can use a loop:

var a = []
for i in range(n):
    a.append(0)  # or a += [0]

Bit disappointed that there’s no such thing, but it’s not a dealbreaker. Thanks.

gax | 2017-09-10 05:48

Agreed, it would be nice, but it’s not a dealbreaker.

Python-style generators would be really nice, too.

kidscancode | 2017-09-10 05:54

As an alternative to doing a for loop, in Godot 3 (at least) you can use the Array’s resize method (if resizing a predefined array with the intention of resetting it, be sure to call the clear() function first):

var a = []
a.resize(n)

https://docs.godotengine.org/en/3.1/classes/class_array.html#class-array-method-resize
https://docs.godotengine.org/en/3.1/classes/class_array.html#class-array-method-clear

Too bad there’s no inline way to initialize an Array of n size. Maybe that’ll come down the road as most languages support the feature. :slight_smile:

Happy coding!

Smij | 2019-06-15 03:21

The compiler complains that you are declaring ‘i’ but not using it. Again, not a deal breaker, just annoying

W 0:00:27.804 The local variable ‘i’ is declared but never used in the block. If this is intended, prefix it with an underscore: ‘_i’
<C++ Error> UNUSED_VARIABLE

Subquadrant.gd:585 [wrap=footnote]grymjack | 2023-03-24 06:42[/wrap]
:bust_in_silhouette: Reply From: Alkhemi

Since godot 3.5, you can do this

var a = []
a.resize(n)
a.fill(0)