0 votes

i know there is custom iterator:

https://docs.godotengine.org/en/latest/tutorials/scripting/gdscript/gdscript_advanced.html#custom-iterators

but is there an easy way to have something like this but with "custom array" ?

i want to do something like this:

var myclass = MyClass.new()
myclass.add("hello")
print( myclass[0] ) -> should print "hello"

no problem if its not possible, but i remember doing this in c#

in Engine by (25 points)

1 Answer

0 votes

I wa asking myself the same question, and as it could be useful, I will answer for anyone wo need it. It's not possible to fast access keys of an object like that, not with numbers. With strings, we still get that complex virtual _get() method, but it is another area.

For purpose a basic example of an object class :

extends Object
var inventory = ["A","B","C","D"]
var i = 0

func _iter_init(arg):
    i = 0
    return i < inventory.size()

func _iter_next(arg):
    i += 1
    return i < inventory.size()

func _iter_get(arg):
    return inventory[i]

func key(n:int):
    return inventory[n]

And here the working code access inside a scene :

tool
extends Node
var object = preload("object.gd").new()

func _ready():
    for each in object : prints(each)

A
B
C
D

An alternative, which use only the key function :

tool
extends Node
var object = preload("object.gd").new()

func _ready():
    prints(object.key(0))

A

by (62 points)
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 Frequently asked questions and 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 [email protected] with your username.