Godot Version
Godot 4.5.2
Question
Hej there! I was wondering if it was possible to use Dictionaries as a drop-in replacement for editor behavior similar to enumerations. Let’s say I have a setup like the following:
var data: Dictionary = {
"data_name_1" : false, "data_name_2" : false, "some_other_data_name": false
}
func print_data(target: String) -> void:
print(data[target])
func foo() -> void:
print_data("da...
Would it be possible to have print_data() auto-suggest entries from data Dictionary while writing?
You’ll need to write it this way:
enum DATA_NAMES {
NAME_1,
NAME_2,
NAME_3,
}
const DATA_NAMES_VALUE: Dictionary = {
DATA_NAMES.NAME_1: false,
DATA_NAMES.NAME_2: false,
DATA_NAMES.NAME_3: false,
}
var data: Dictionary = {
"data_name_1" : false, "data_name_2" : false, "some_other_data_name": false
}
func print_data(target: DATA_NAMES) -> void:
print(data[DATA_NAMES.NAME_1])
No, it’s hard enough to discern a runtime dictionary’s keys are of interest, furthermore difficult by the function taking in a general String. You could use a different text editor, vim for instance will recommend nearly any typed whole word, but this is pretty strange behavior and actually ends up being a very stupid autocomplete on it’s own.
Godot’s code editor only checks for very specific magic strings.
Using enums as keys would be much better, is there any reason you aren’t using them already? Can you explain your actual use case?
I implemented achievements and their unlock state as a Dictionary. I hoped, that this way I could have them all in one place. If I kept them as enums, that would duplicate the effort, no?
Enums shouldn’t duplicate effort or code, only replace your strings. FreakyGoose’s example isn’t great since it keeps your data dictionary where it doesn’t need to and the print_data sample is wrong in a couple ways.
enum Achievement {
TOUCHED_SPIKES,
TOUCHED_GRASS,
GOT_STAR,
GOT_KEY
}
var unlocks: Dictionary[Achievement, bool] = {}
func unlock_one_achievement(type: Achievement) -> void:
unlocks[type] = true
func check_unlocked_achievement(type: Achievement) -> bool:
return unlocks.get(type, false)
## Then in use:
unlock_one_achievement(Achievement.TOUCHED_GRASS) # everything auto-completes, no strings!
That is a fair solution, yes. Thank you.
I am a big fan of readable strings where possible, so on third party APIs I can use the same achievement strings instead of ints (in this example). Yet, something has got to give 