Is there another way to iteate an array reversed?

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

Still i use this to iterate an array of instances backwards:

var size = group_node.get_children().size()
for i in range(size - 1, -1, -1):
    if group_node.get_children()[i].level > 0:
        G.curency += group_node.get_children()[i].units_second
    return

to find the last one, that is already leveled in the game and use it to add a matching value to the curency.

but is there also another way?
one, that is more like:

for instance in group_node.get_children():
    if instance.level > 0:
        G.curency += instance.units_second

That the variable, that is declared in the for-line here “instance”, directly holds an instance from these children and not just a number. but this goes forward

:bust_in_silhouette: Reply From: jgodfrey

One way would be to just reverse the order of the original array prior to iterating over it (via the array’s invert() method). So, something like this:

var instances = group_node.get_children()
instances.invert() # <-- reverse the array order
for instance in instances:
    if instance.level > 0:
        G.curency += instance.units_second

now i used your way.

Drachenbauer | 2022-04-10 15:01

:bust_in_silhouette: Reply From: aipie

You could also create you own var and use it futher down the code

var size = group_node.get_children().size()
for i in range(size - 1, -1, -1):
    var instance = group_node.get_children()[i]
    if instance.level > 0:
        G.curency += instance.units_second
    return