summaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
authorNonunknown <nonunknown777@gmail.com>2022-10-15 09:43:16 -0300
committerNonunknown <nonunknown777@gmail.com>2022-10-20 08:39:47 -0300
commit9f4dbf415da6d150788915cb35a9c3dc7f04c547 (patch)
tree8168471787ca3bcb55371a67e4aa4d4efb444aca /core
parentdc4b6165962536b53c4c1471fcf0be43c70e2335 (diff)
add ability to pick random value from array
Diffstat (limited to 'core')
-rw-r--r--core/variant/array.cpp6
-rw-r--r--core/variant/array.h1
-rw-r--r--core/variant/variant_call.cpp1
3 files changed, 8 insertions, 0 deletions
diff --git a/core/variant/array.cpp b/core/variant/array.cpp
index 8b958814db..c6bbd43dc4 100644
--- a/core/variant/array.cpp
+++ b/core/variant/array.cpp
@@ -31,6 +31,7 @@
#include "array.h"
#include "container_type_validate.h"
+#include "core/math/math_funcs.h"
#include "core/object/class_db.h"
#include "core/object/script_language.h"
#include "core/templates/hashfuncs.h"
@@ -299,6 +300,11 @@ Variant Array::back() const {
return operator[](_p->array.size() - 1);
}
+Variant Array::pick_random() const {
+ ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
+ return operator[](Math::rand() % _p->array.size());
+}
+
int Array::find(const Variant &p_value, int p_from) const {
ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find"), -1);
return _p->array.find(p_value, p_from);
diff --git a/core/variant/array.h b/core/variant/array.h
index 3d9a794969..ee265a9ffd 100644
--- a/core/variant/array.h
+++ b/core/variant/array.h
@@ -79,6 +79,7 @@ public:
Variant front() const;
Variant back() const;
+ Variant pick_random() const;
void sort();
void sort_custom(const Callable &p_callable);
diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp
index 900e3d8e77..ef4807ba71 100644
--- a/core/variant/variant_call.cpp
+++ b/core/variant/variant_call.cpp
@@ -2053,6 +2053,7 @@ static void _register_variant_builtin_methods() {
bind_method(Array, erase, sarray("value"), varray());
bind_method(Array, front, sarray(), varray());
bind_method(Array, back, sarray(), varray());
+ bind_method(Array, pick_random, sarray(), varray());
bind_method(Array, find, sarray("what", "from"), varray(0));
bind_method(Array, rfind, sarray("what", "from"), varray(-1));
bind_method(Array, find_last, sarray("value"), varray());