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:
- Object.get_script() – returns an instance of Script
- Resource.resource_path – Script inherits from Resource
- String.get_base_dir() – the resource_path is a string
- String.path_join()
- built-in function load()