diff --git a/core/variant/dictionary.cpp b/core/variant/dictionary.cpp index 141ce25fa6e..8b61a8993a1 100644 --- a/core/variant/dictionary.cpp +++ b/core/variant/dictionary.cpp @@ -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(); } diff --git a/core/variant/dictionary.h b/core/variant/dictionary.h index 8935d35ed91..f94a0da80a1 100644 --- a/core/variant/dictionary.h +++ b/core/variant/dictionary.h @@ -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; diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp index f041d2c95ee..7121b4da96c 100644 --- a/core/variant/variant_call.cpp +++ b/core/variant/variant_call.cpp @@ -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()); diff --git a/doc/classes/Dictionary.xml b/doc/classes/Dictionary.xml index 955d80fcb76..7a5e51e4ef3 100644 --- a/doc/classes/Dictionary.xml +++ b/doc/classes/Dictionary.xml @@ -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. + + + + + + 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. + +