Iterate through and access a custom class the same way you can with an array?

Godot Version

4.3

Question

I have a custom class which has it’s own array as a variable kind of like this

class_name CustomClass extends Node
var data = []
#some other bits of code and functions

what I’d like to do is to be able to iterate through and access that class as if it were just a regular array, preferably without having to type CustomClass.data every time if that makes sense

#something like this
var temp = CustomClass.new()
for i in temp:
     for j in range(5):
          print(i == temp[j])

You can give your class a custom iterator.
Here is an example (modified version of the documentation code)

class_name Test extends Node2D

var start:int = 0
var current:int = 0
var end:int
var increment:int = 1
var tt:Array[int] = [1, 2, 3, 6, 12, 24]

func should_continue():
	return (current < end)

func _iter_init(arg):
	end = tt.size()
	current = start
	return should_continue()

func _iter_next(arg):
	current += increment
	return should_continue()

func _iter_get(arg):
	return tt[current]

Iterating the class:

func _ready() -> void:
	var t:Test = Test.new()
	for n in t: 
		print(n)

And the output:

1
2
3
6
12
24
1 Like

is there not a way for me to use the [] operator then?

Godot does not support operator overloading, (outside of _str and iterators) I wouldn’t be surprised if they added it but it’s a very low priority feature with iterators already in.

Not sure what your use case is. If you want to access data, you have to use .data.

If your class is only for storing an array, why do you need the class at all?

Is there a need to use [ ]?

class_name CustomClass extends Node
var data = []   
func is_equal_to(i:int, index:int)->bool: 
    return data[iindex] == i
var temp = CustomClass.new()
for i in temp:
     for j in range(5):
          #print(i == temp[j])
          print(temp.is_equal_to(i, j))

I like the idea of operator overloading.
Here is the most recent proposal I could find in regards to operator overloading.
Right now its about 200th most popular so go there and add a plus to shift it up the list.