#Can I access an Object with array brackets, like foo[12] in Godot?
1 messages · Page 1 of 1 (latest)
Kinda. When you use brackets on an object. it'll just act like a getter.
For example
var something := "Test"
func _ready() -> void:
print(self["something"])
This will print test.
Thanks for your time, yeah but that would not allow me to do self[0] 🤔
Unfortunately there is no way to do that yet (accessing as-is by index). You can technically make a workaround by getting the property list on said object and then check what index it is. But at the end of the day you still technically would still be using a String
Yeah, meh! Thanks though ❤️
This is the closest thing i can think of. Both would print the same thing
var something := "Test"
func _ready() -> void:
# zero would be pointing to the script
print(self["1"])
print(self.get("1"))
func _get(property: StringName) -> Variant:
if not property.is_valid_int():
return null
var properties = get_script().get_script_property_list()
var script_property = properties.get(int(property))
var result = get(script_property.name)
return result
Again this is still actually using a String but its the closest thing to what you wanted.
this would return something right?
I'm looking for a shorthand so Foo[0] returns Foo.results[0]
But I could also use a String for that. I thought of that approach but then I'd prefer a .get_index(i: int) method
Yep it would return something. If you want to make a custom function then its even easier as you can constraint the type to only accept int. But yeah no Foo[0] as-is. Either a workaround or make a function that returns the variable from the property list.