godotengine / godot-proposals

Godot Improvement Proposals (GIPs)
MIT License
1.16k stars 97 forks source link

Add static keys completion for Dictionary in the script editor #10354

Open Thorgrimar opened 3 months ago

Thorgrimar commented 3 months ago

Describe the project you are working on

Any project where I use dictionaries, especially to use it as .json save file with lots of static keys.

Describe the problem or limitation you are having in your project

It's difficult to not make a mistake when typing the string key to access the desired value in a dictionary, with dict.get("key_name"). Godot allows the syntax dict.key_name but the completion of the identifier only appear if the dictionary is const.

gd dict The completion doesn't display lua_key even though the script works.

Describe the feature / enhancement and how it helps to overcome the problem or limitation

Display the list of the keys as identifiers, like when the dictionary is constant. It makes a lot of sense for LUA style dict where keys are defined as identifiers. Of course, for non const dict, the key may be erased at execution, but it is the same for the .get("key") syntax.

Describe how your proposal will work, with code, pseudo-code, mock-ups, and/or diagrams

I think this dict->is_constant is responsible for this behavior. https://github.com/godotengine/godot/blob/3978628c6cc1227250fc6ed45c8d854d24c30c30/modules/gdscript/gdscript_editor.cpp#L816

If this enhancement will not be used often, can it be worked around with a few lines of script?

You have to create a enum with all the keys, and use the completion of enums.

enum KeyNames {
    key_apple,
    key_cherry,
}

var enum_dict = {
    KeyNames.key_apple: 0,
    KeyNames.key_cherry: 1,
}

print(enum_dict[KeyNames.key_cherry])

Is there a reason why this should be core and not an add-on in the asset library?

It's part of the Godot Editor.

Thorgrimar commented 2 months ago

I'm not clear sorry. It's very simple : I wish to remove the dict->is_constant at this line https://github.com/godotengine/godot/blob/3978628c6cc1227250fc6ed45c8d854d24c30c30/modules/gdscript/gdscript_editor.cpp#L816. if that breaks nothing.

That way, the auto completion will display the keys you have previously stored in your dictionary.

HolonProduction commented 2 months ago

It breaks nothing per se, but it breaks the users assumption that the autocompletion options can be trusted (which admittedly might not always be true, but we at least aim for it).

The request has come up multiple times and I'd say it is mostly an editor workaround to compensate for the absence of structs in GDScript.

We could consider changing this behavior temporarily and revert it when/if structs are implemented.

Edit: Also the line of code you linked has nothing to do with this behavior.