Skip to content

Commit

Permalink
[Core] Add Dictionary.set for read-only enforcing assignments
Browse files Browse the repository at this point in the history
Matches the one on `Array`, otherwise functions like the `[]` operator
  • Loading branch information
AThousandShips committed Oct 24, 2024
1 parent e686002 commit 8d9afa5
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
7 changes: 7 additions & 0 deletions core/variant/dictionary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,13 @@ Variant *Dictionary::getptr(const Variant &p_key) {
}
}

void Dictionary::set(const Variant &p_key, const Variant &p_value) {
ERR_FAIL_COND_MSG(_p->read_only, "Dictionary is in read-only state.");
Variant key = p_key;
ERR_FAIL_COND(!_p->typed_key.validate(key, "set"));
operator[](key) = p_value;
}

Variant Dictionary::get_valid(const Variant &p_key) const {
Variant key = p_key;
ERR_FAIL_COND_V(!_p->typed_key.validate(key, "get_valid"), Variant());
Expand Down
1 change: 1 addition & 0 deletions core/variant/dictionary.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class Dictionary {
const Variant *getptr(const Variant &p_key) const;
Variant *getptr(const Variant &p_key);

void set(const Variant &p_key, const Variant &p_value);
Variant get_valid(const Variant &p_key) const;
Variant get(const Variant &p_key, const Variant &p_default) const;
Variant get_or_add(const Variant &p_key, const Variant &p_default);
Expand Down
4 changes: 4 additions & 0 deletions tests/core/variant/test_dictionary.h
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ TEST_CASE("[Dictionary] Assignment using bracket notation ([])") {
ERR_PRINT_OFF;
CHECK(int(map.get_or_add("This key does not exist", String()).get_type()) == Variant::NIL);
CHECK(map.size() == length);

map.set("This key does not exist", String());
CHECK_FALSE(map.has("This key does not exist"));
CHECK(map.size() == length);
ERR_PRINT_ON;
}

Expand Down

0 comments on commit 8d9afa5

Please sign in to comment.