Duck typing when adding new fields in an autoloaded class

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

I have a following autoloaded class A:

extends Node
var asdf = null
func _ready():
  set("asdf", "test")

and another node B somewhere else in the tree:

extends Node
func _ready():
  print(A.asdf)

The code then works fine and prints test. However, I’d like to add different fields programmatically without explicitly listing them first, eg.:

extends Node
func _ready():
  set("asdf", "test")

However, when I do this:

extends Node
func _ready():
  print("asdf" in A)
  print(A.asdf)

I’m getting False and and invalid_get_index. Is it possible to access the dynamically-created fields in autoloaded classes?

:bust_in_silhouette: Reply From: omggomb

You need to use a backing dictionary in your autoloaded class, then override the _set and _get methods. And then use A.get and A.set instead.

definition of A

extends Node
var my_props = {}
func _set(property, value):
    my_props[property] = value

func _get(property):
    return my_props[property]

usage

A.set("name", "Hi")
print(A.get("name")) # will print "Hi"

As per this doc page access with A.name should be possible by overiding _get_property_list() but I didn’t get this to work: See this doc page for an example of _get_property_list()

TLDR: Might as well use dictionary directly if you don’t need editor support for editing dynamic properties.