Skip to content

Commit

Permalink
Add a get_or_add method to Dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronfranke committed Dec 6, 2023
1 parent 2f73a05 commit 437586b
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions core/variant/dictionary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,15 @@ Variant Dictionary::get(const Variant &p_key, const Variant &p_default) const {
return *result;
}

Variant Dictionary::get_or_add(const Variant &p_key, const Variant &p_default) {
const Variant *result = getptr(p_key);
if (!result) {
operator[](p_key) = p_default;
return p_default;
}
return *result;
}

int Dictionary::size() const {
return _p->variant_map.size();
}
Expand Down
1 change: 1 addition & 0 deletions core/variant/dictionary.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class Dictionary {

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);

int size() const;
bool is_empty() const;
Expand Down
1 change: 1 addition & 0 deletions core/variant/variant_call.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2195,6 +2195,7 @@ static void _register_variant_builtin_methods() {
bind_method(Dictionary, values, sarray(), varray());
bind_method(Dictionary, duplicate, sarray("deep"), varray(false));
bind_method(Dictionary, get, sarray("key", "default"), varray(Variant()));
bind_method(Dictionary, get_or_add, sarray("key", "default"), varray(Variant()));
bind_method(Dictionary, make_read_only, sarray(), varray());
bind_method(Dictionary, is_read_only, sarray(), varray());

Expand Down
8 changes: 8 additions & 0 deletions doc/classes/Dictionary.xml
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,14 @@
Returns the corresponding value for the given [param key] in the dictionary. If the [param key] does not exist, returns [param default], or [code]null[/code] if the parameter is omitted.
</description>
</method>
<method name="get_or_add">
<return type="Variant" />
<param index="0" name="key" type="Variant" />
<param index="1" name="default" type="Variant" default="null" />
<description>
Gets a value and ensures the key is set. If the [param key] exists in the dictionary, this behaves like [method get]. Otherwise, the [param default] value is inserted into the dictionary and returned.
</description>
</method>
<method name="has" qualifiers="const">
<return type="bool" />
<param index="0" name="key" type="Variant" />
Expand Down

0 comments on commit 437586b

Please sign in to comment.