godot icon indicating copy to clipboard operation
godot copied to clipboard

Add `Dictionary.find()`

Open KoBeWi opened this issue 3 years ago • 3 comments
trafficstars

I use enum.keys().find(key) to reverse-lookup an enum value saved as string. The problem is that keys() dumps all keys into an array, so keys().find() first extracts the array and then finds value in the array, which is just bad :/ The new method skips the extraction part and is ~10x faster.

I also added some unit tests.

KoBeWi avatar Aug 05 '22 17:08 KoBeWi

I understand this is for dealing with enums. But for a normal dictionary, null is a valid key, so Dictionary.find() won't be able to distinguish between found and not found in that case. I think it's worth documenting if acceptable.

timothyqiu avatar Aug 06 '22 09:08 timothyqiu

for a normal dictionary, null is a valid key, so Dictionary.find() won't be able to distinguish between found and not found in that case. I think it's worth documenting if acceptable.

Current description in the docs is correct and implies this though. But I guess that case can be mentioned explicitly.

var key = dict.find(value)

# Correct check:
var found: bool = key != null or null in dict

# Same as: (wondering if it could end up being cheaper because of the GDScript overhead)
var found: bool = key in dict

kleonc avatar Aug 06 '22 10:08 kleonc

I added some note about, I don't think anything more is necessary. I bet null as a Dictionary key is not used very often and even less with find().

KoBeWi avatar Aug 06 '22 20:08 KoBeWi

Thanks!

akien-mga avatar Sep 01 '22 15:09 akien-mga

Should be backported manually if wanted in 3.x.

akien-mga avatar Sep 05 '22 13:09 akien-mga