From b3f93ad127cc2a840b253f397ce135fd10dc666c Mon Sep 17 00:00:00 2001 From: SysError99 Date: Thu, 15 Feb 2024 05:03:39 +0700 Subject: [PATCH] [3.x] Add a `get_or_add` method to Dictionary Co-authored-by: Aaron Franke --- core/dictionary.cpp | 9 +++++++++ core/dictionary.h | 1 + core/variant_call.cpp | 2 ++ doc/classes/Dictionary.xml | 8 ++++++++ 4 files changed, 20 insertions(+) diff --git a/core/dictionary.cpp b/core/dictionary.cpp index c672e2691bb2..b8a57218541c 100644 --- a/core/dictionary.cpp +++ b/core/dictionary.cpp @@ -116,6 +116,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/dictionary.h b/core/dictionary.h index e0e5cf0cd802..dad679f30b44 100644 --- a/core/dictionary.h +++ b/core/dictionary.h @@ -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 empty() const; diff --git a/core/variant_call.cpp b/core/variant_call.cpp index 918553af6591..b63f335a07b6 100644 --- a/core/variant_call.cpp +++ b/core/variant_call.cpp @@ -559,6 +559,7 @@ struct _VariantCall { VCALL_LOCALMEM0R(Dictionary, values); VCALL_LOCALMEM1R(Dictionary, duplicate); VCALL_LOCALMEM2R(Dictionary, get); + VCALL_LOCALMEM2R(Dictionary, get_or_add); VCALL_LOCALMEM2(Array, set); VCALL_LOCALMEM1R(Array, get); @@ -1944,6 +1945,7 @@ void register_variant_methods() { ADDFUNC0R(DICTIONARY, ARRAY, Dictionary, values, varray()); ADDFUNC1R(DICTIONARY, DICTIONARY, Dictionary, duplicate, BOOL, "deep", varray(false)); ADDFUNC2R(DICTIONARY, NIL, Dictionary, get, NIL, "key", NIL, "default", varray(Variant())); + ADDFUNC2R(DICTIONARY, NIL, Dictionary, get_or_add, NIL, "key", NIL, "default", varray(Variant())); ADDFUNC0R(ARRAY, INT, Array, size, varray()); ADDFUNC0R(ARRAY, BOOL, Array, empty, varray()); diff --git a/doc/classes/Dictionary.xml b/doc/classes/Dictionary.xml index 166bc74ea0f1..a3cc577424f0 100644 --- a/doc/classes/Dictionary.xml +++ b/doc/classes/Dictionary.xml @@ -131,6 +131,14 @@ Returns the current value for the specified key in the [Dictionary]. If the key does not exist, the method returns the value of the optional default argument, or [code]null[/code] if it is omitted. + + + + + + Gets a value and ensures the key is set. If the [code]key[/code] exists in the dictionary, this behaves like [method get]. Otherwise, the [code]default[/code] value is inserted into the dictionary and returned. + +