Including other files as module is ... interesting

GDscript makes it interesting to include/import other files.

For the resistor-color-* exercises, I like to just include the previous ones so I’m not copy-pasting.

GDscript forces you to handle *.gd files as classes. For example, If I have files resistor_color_duo.gd and resistor_color.gd, then the -duo script starts with

var ResistorColor = load(resource path of resistor_color)
var rc = ResistorColor.new()

# Now I can do:
var code = rc.color_code("yellow")

That’s a little extra boilerplate than I’d like, but it makes sense in a game dev perspective.

The real tricky part is the resource path. Working locally, the test runner is running in the current directory with the solution files, so this is fine:

var ResistorColor = load("res://resistor_color.gd")

But after you submit the gdscript test runner has quite a different behaviour. It errors quite spectacularly. The lengthy error message starts with

ERROR: Attempt to open script 'res://resistor_color.gd' resulted in error 'File not found'.
   at: load_source_code (modules/gdscript/gdscript.cpp:1139)
   GDScript backtrace (most recent call first):
       [0] @implicit_new (/mnt/exercism-iteration/resistor_color_duo.gd:1)
...

The clue there is the path to the resistor_color_duo.gd script: I’ll have to be more specific about the location of the file I want to include. I have to specify that it’s in the same directory as the currently executing file.

With a bit of AI help, this is the magic recipe

var current_path = get_script().resource_path.get_base_dir()
var ResistorColor = load(current_path.path_join("resistor_color.gd"))

docs:

1 Like

If you are using GoDot Engine and the IDE, you can just add class_name Foo to the file then Foo automagically becomes available to other files in the same project/directory.

I’m a bit confused why this only works through the engine/IDE.

You can give your class a name to register it as a new type in Godot’s editor.

GDScript reference — Godot Engine (stable) documentation in English