Merge pull request #78095 from aaronfranke/dict-get-or-set-default

Add a `get_or_add` method to Dictionary
This commit is contained in:
Yuri Sizov 2023-12-16 17:49:10 +01:00
commit d02b368fd6
4 changed files with 19 additions and 0 deletions

View File

@ -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();
}

View File

@ -58,6 +58,7 @@ public:
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;

View File

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

View File

@ -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" />