Search code examples
structnestedgdscript

How do I implement a nested structure in gdscript?


I found this question on how to make a structure: How do I implement structures in GDScript?

I tried using the suggestions to make a nested structure, but couldn't figure out how.

The following dictionary way doesn't work:

# doesn't work
var stuct = {
  foo = 1
  nested = {
    bar = 2
  }
}

Nor does the following class way:

# doesn't work
class struct:
    static var foo: Number
    class inner:
        static var bar: Number

If I don't define the type of foo in the class way, then I can get it to work. But I would like to have all my types set up. I also do not have values for all variables in my real world case, some need to be set by external operations.


Solution

  • Dictionaries are comma separated:

    var stuct = {
        foo = 1, # <- Notice the comma
        nested = {
            bar = 2
        }
    }
    

    About the class, I don't know what the type Number you are using is. And for what you say, I'm guessing neither does Godot. However, if it is defined and in scope then it should work.

    Be aware that defining your classes with class does not put them in the global scope. See Using a custom class in Godot.

    Aside from that, have a look at the list of build-in types in GDScript. Perhaps int or float would do?