Forráskód Böngészése

Add a `get_or_add` method to Dictionary

Aaron Franke 2 éve
szülő
commit
437586bf31

+ 9 - 0
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();
 }

+ 1 - 0
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;

+ 1 - 0
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());
 

+ 8 - 0
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.
 			</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" />