Looping backwards over an array

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By julkip

I have an array over which I have to iterate forwards and backwards, depending on circumstances.

Is there a better way than just to use
var array = ["A", "B", "C", "D"]
var array_backwards = ["D", "C", "B", "A"]
and use each array accordingly? My first instinct was to use the invert() function, but I saw that this does not return the array inverted, but inverts it in place. I guess I could probably use array.duplicate().invert() instead of declaring it by hand, but this also seems a bit clunky to me.

You can do this by using an index and inverting the step:

for i in range(10, 0, -1):
	print(i)

But that prints:

10
9
8
7
6
5
4
3
2
1

So either range(9, -1, -1) or use i-1?

Zylann | 2019-08-06 19:23

:bust_in_silhouette: Reply From: Fattywithhacks

var array = ["A", "B", "C", "D"]
var arrayinv = []
func _ready():
arrayinv = array.duplicate()
arrayinv.invert()
print(arrayinv)
pass
Works great but you could also use:
var array = ["A", "B", "C", "D"]
var arrayinv =[]
func _ready():
for i in array:
arrayinv.push_front(i)
print(arrayinv)
pass

hope i could help :slight_smile:

:bust_in_silhouette: Reply From: IHate

It’s and old post but this is another possible solution:

for x in array.size():
  var value = array[-x-1]

Negative index goes backwards.

var x = [1, 2, 3, 4, 5]

for i in range(x.size()-1, -1, -1):
    var element = x[i]
    print(element)
# output = 5, 4, 3, 2, 1

NikhilKadiyan | 2021-06-12 14:36