1

I have a GDScript file, and I would like to be able to run a block of code whenever the script is loaded. I know _init will run whenever an instance is constructed and _ready will run when it's added to the scene tree. I want to run code before either of those events happens; when the preload or load that brings it into memory first happens.

In Java, this would be a static initializer block, like so

public class Example {
    public static ArrayList<Integer> example = new ArrayList<Integer>;
    static {
        // Pretend this is a complicated algorithm to compute the example array ...
        example.add(1);
        example.add(2);
        example.add(3);
    }
}

I want to do the same thing with a GDScript file in Godot, where some top-level constant or other configuration data is calculated when the script is first loaded, something like (I realize this is not valid GDScript)

extends Node
class_name Example

const EXAMPLE = []

static:
    EXAMPLE.push_back(1)
    EXAMPLE.push_back(2)
    EXAMPLE.push_back(3)

Is there some way to get a feature like this or even to approximate it?

Background Information: The reason I care (aside from a general academic interest in problems like these) is that I'm working on a scripting language that uses GDScript as a compile target, and in my language there are certain initialization and registration procedures that need to happen to keep my language's runtime happy, and this needs to happen whenever a new script from my language is loaded.

In reality the thing I want to do is basically going to be

static:
    MyLanguageRuntime.register_class_file(this_file, ...)

where MyLanguageRuntime is a singleton node that exists at the top of the scene tree to keep everything running smoothly.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • 1
    you tried to use "Autoloads" ? – Ahmed El-Tabarani Mar 19 '21 at 22:42
  • Autoloads run at the start of the entire game. It's viable, I suppose, but it would subvert Godot's nice scene loading mechanics. I really want to run something when the particular file resource is loaded, not when the whole program is started up. – Silvio Mayolo Mar 20 '21 at 04:33
  • 2
    Maybe you could try to implement custom `ResourceFormatLoader` for your files and call a custom "static" function yourself. I didn't try to use that though. https://docs.godotengine.org/uk/stable/classes/class_resourceformatloader.html – Oliort UA Mar 20 '21 at 15:06

0 Answers0