Array iterating

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

Hello!
I have var arr = Array()
How can I iterate all objects of this array with access to their funcs?

:bust_in_silhouette: Reply From: Gokudomatic2

I can’t test it right now but I guess it’s something like

var arr = Array()
# populate the array
for item in arr:
  item.my_func()
  item.my_prop=some_value

Or this if you need the index:

for i in range(0, arr.size():
    print("Accessing item at index " + str(i))
    arr[i].my_func()

Zylann | 2016-08-22 12:37

:bust_in_silhouette: Reply From: 201Dev

You can iterate over arrays with a for loop: GDScript reference — Godot Engine (latest) documentation in English
You can’t store functions in variables or arrays in GD script but you can reference them:

# Call a function by name in one step
mynode.call("myfunction", args)

# Store a function reference
var myfunc = funcref(mynode, "myfunction")
# Call stored function reference
myfunc.call_func(args)
:bust_in_silhouette: Reply From: MathieuJazz

First, note that you can build your array using the Inspector:

export var arr = ["obj_1", "obj_2"]

You’ll be able to change the variable type in the inspector.

Then, you will have to loop in your array using while or for.

#loop in arr
var i = 0
while i < arr.size():
    #Access func
	arr[i].func_name()

    #Acces or change var
    arr[i].var_name = 1

    #Then iterate to avoid infinite loop!!
    i+=1
  1. First be sure they all have the same scripts, or at least the same func name!
  2. Looping in large array and accessing their funcs can get your game laggy
  3. Avoid death loops! (Always add i+=1 in the loop)