Is there a way to overload the `load` function in a GDScript?

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

I’m trying to make some dynamic objects for testing purposes. If I was able to overload the load function it would save me a WORLD of trouble. I don’t really care how ugly it is to do.

The more abstract issue is that I’m trying to mock objects that are loaded by a given script. I need to replace calls to load and preload to another method that will return the mocked scripts instead of what they are really trying to load. I’m already writing a new file based on the original, so I can replace the load and preload strings I find but that only works in trivial cases. If I want to be absolutely sure that I get them all and I’m not replacing load in the middle of some string, I’ll have to make a complicated parsing algorithm.

:bust_in_silhouette: Reply From: Zylann

preload and load are global builtin functions, and GDScript doesn’t allow global functions to be defined, so no, you can’t override them in the strict sense.
Also, preload is quite hard to override without losing the parse-time feature of it.

However, you can “override” load…by not using it.
Just write your own load function, which may wrap a call to load or your custom mock resources, and call that one instead of load directly. You can do this by creating an auto-load singleton, which you would call like this:

var resource = MyResourceLoader.load("some_asset.tscn")

That’s what I was afraid of. I’m trying to make a tool, so expecting others to load their things a certain way just so they can use the tool is slightly more gross than parsing text. Thanks.

bitwes | 2018-03-07 23:37