1
0
mirror of https://github.com/godotengine/godot.git synced 2025-11-06 12:20:30 +00:00

Add an Array.pop_at() method to pop an element at an arbitrary index

Negative indices are supported to pop an element relative from the end.
This commit is contained in:
Hugo Locurcio
2021-08-27 01:27:07 +02:00
parent ac33441b94
commit d717eb537b
4 changed files with 39 additions and 3 deletions

View File

@@ -363,8 +363,8 @@ void Array::push_front(const Variant &p_value) {
Variant Array::pop_back() {
if (!_p->array.empty()) {
int n = _p->array.size() - 1;
Variant ret = _p->array.get(n);
const int n = _p->array.size() - 1;
const Variant ret = _p->array.get(n);
_p->array.resize(n);
return ret;
}
@@ -373,13 +373,38 @@ Variant Array::pop_back() {
Variant Array::pop_front() {
if (!_p->array.empty()) {
Variant ret = _p->array.get(0);
const Variant ret = _p->array.get(0);
_p->array.remove(0);
return ret;
}
return Variant();
}
Variant Array::pop_at(int p_pos) {
if (_p->array.empty()) {
// Return `null` without printing an error to mimic `pop_back()` and `pop_front()` behavior.
return Variant();
}
if (p_pos < 0) {
// Relative offset from the end
p_pos = _p->array.size() + p_pos;
}
ERR_FAIL_INDEX_V_MSG(
p_pos,
_p->array.size(),
Variant(),
vformat(
"The calculated index %s is out of bounds (the array has %s elements). Leaving the array untouched and returning `null`.",
p_pos,
_p->array.size()));
const Variant ret = _p->array.get(p_pos);
_p->array.remove(p_pos);
return ret;
}
Variant Array::min() const {
Variant minval;
for (int i = 0; i < size(); i++) {