+2 votes

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.

in Engine by (47 points)

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?

2 Answers

+1 vote

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 :)

by (32 points)
+3 votes

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.

by (397 points)
edited by
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
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.