Skip to content

Commit d02b368

Browse files
committed
Merge pull request #78095 from aaronfranke/dict-get-or-set-default
Add a `get_or_add` method to Dictionary
2 parents ca19d34 + 437586b commit d02b368

4 files changed

Lines changed: 19 additions & 0 deletions

File tree

core/variant/dictionary.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,15 @@ Variant Dictionary::get(const Variant &p_key, const Variant &p_default) const {
150150
return *result;
151151
}
152152

153+
Variant Dictionary::get_or_add(const Variant &p_key, const Variant &p_default) {
154+
const Variant *result = getptr(p_key);
155+
if (!result) {
156+
operator[](p_key) = p_default;
157+
return p_default;
158+
}
159+
return *result;
160+
}
161+
153162
int Dictionary::size() const {
154163
return _p->variant_map.size();
155164
}

core/variant/dictionary.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ class Dictionary {
5858

5959
Variant get_valid(const Variant &p_key) const;
6060
Variant get(const Variant &p_key, const Variant &p_default) const;
61+
Variant get_or_add(const Variant &p_key, const Variant &p_default);
6162

6263
int size() const;
6364
bool is_empty() const;

core/variant/variant_call.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2195,6 +2195,7 @@ static void _register_variant_builtin_methods() {
21952195
bind_method(Dictionary, values, sarray(), varray());
21962196
bind_method(Dictionary, duplicate, sarray("deep"), varray(false));
21972197
bind_method(Dictionary, get, sarray("key", "default"), varray(Variant()));
2198+
bind_method(Dictionary, get_or_add, sarray("key", "default"), varray(Variant()));
21982199
bind_method(Dictionary, make_read_only, sarray(), varray());
21992200
bind_method(Dictionary, is_read_only, sarray(), varray());
22002201

doc/classes/Dictionary.xml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,14 @@
194194
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.
195195
</description>
196196
</method>
197+
<method name="get_or_add">
198+
<return type="Variant" />
199+
<param index="0" name="key" type="Variant" />
200+
<param index="1" name="default" type="Variant" default="null" />
201+
<description>
202+
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.
203+
</description>
204+
</method>
197205
<method name="has" qualifiers="const">
198206
<return type="bool" />
199207
<param index="0" name="key" type="Variant" />

0 commit comments

Comments
 (0)