How to make a globals dictionary with autocomplete?

Godot Version

4.2

Question

I have a globals.gd that is loaded as a singleton/autoload.
on that globals.gd I have a dictionary:

var nodes = {  
    "special_node": null  
}  

Then I have another script, special.gd that is a class_name

class_name SpecialNode  

func _init():
    Globals.nodes.special_node = self

func magic():  
    pass  

Then on another script I can call a function:

func _ready():
    Globals.nodes.special_node.magic()

###############################
It all works just as I want, the setback that I have is that there’s no autocomplete.
I can type Globals.nodes. with autocomplete, but after that the editor doesn’t know that I have a “special_node” on the dictionary. After that I would also like the editor to autocomplete all the way “Globals.nodes.special_node.magic”, so up to the function.

What change do I need to do on the globals.gd “nodes” dictionary, so that I can get autocomplete?

I don’t think that is possible, here is a related issue:

Unfortunately, dictionaries don’t offer type support, so autocompletion won’t work for them.
If you want to rely on autocompletion, you could instead use a class:

# my_nodes_class.gd
extends RefCounted
class_name MyNodes

var special_node : Node

Your singleton script could then look like this:

# globals.gd
var nodes := MyNodes.new()

And in your special.gd script, you could then do the same as you did before,
but this time it autocompletes the nodes.special_node member:

# special.gd
class_name SpecialNode

func _init():
    Globals.nodes.special_node = self
1 Like

I’ve tried that, and what you say makes sense, but somehow I still don’t get autocomplete.
After typing “Globals.nodes.s” no suggestion comes up.

Are you sure you defined the type of the nodes variable in your globals script?

If you followed the answer you got, your globals script should look something like this:

var nodes := MyNodes.new()

or

var nodes: MyNodes = MyNodes.new()