Skip to content

Commit

Permalink
Core: Fix operator[] for typed dictionaries
Browse files Browse the repository at this point in the history
  • Loading branch information
Repiteo committed Sep 10, 2024
1 parent 97ef3c8 commit 3e52612
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 4 deletions.
17 changes: 13 additions & 4 deletions core/variant/dictionary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,25 @@ Variant Dictionary::get_value_at_index(int p_index) const {
}

Variant &Dictionary::operator[](const Variant &p_key) {
if (unlikely(_p->read_only)) {
if (likely(_p->variant_map.has(p_key))) {
*_p->read_only = _p->variant_map[p_key];
Variant key = p_key;
if (unlikely(!_p->typed_key.validate(key))) {
if (_p->typed_fallback == nullptr) {
_p->typed_fallback = memnew(Variant);
} else {
*_p->typed_fallback = Variant();
}

return *_p->typed_fallback;
} else if (unlikely(_p->read_only)) {
if (likely(_p->variant_map.has(key))) {
*_p->read_only = _p->variant_map[key];
} else {
*_p->read_only = Variant();
}

return *_p->read_only;
} else {
return _p->variant_map[p_key];
return _p->variant_map[key];
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
func get_key():
return "key"

func test():
var typed: Dictionary[int, int]
typed[get_key()] = 0
print('not ok')
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
GDTEST_ANALYZER_ERROR
Invalid index type "String" for a base of type "Dictionary[int, int]".
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
func get_key() -> Variant:
return "key"

func test():
var typed: Dictionary[int, int]
typed[get_key()] = 0
print('not ok')
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
GDTEST_RUNTIME_ERROR
>> ERROR
>> Method/function failed. Returning: false
>> Attempted to use a variable of type 'String' into a TypedDictionary.Key of type 'int'.
not ok

0 comments on commit 3e52612

Please sign in to comment.