Open Mercerenies opened 1 year ago
I think that when implementing new functions, it's good to make them as flexible as possible if that doesn't add much code. Why forcing user to get undefined, when with few characters more, we can define any default value that should be returned in that case:
function array_get_safe(_array, _index, _default = undefined) {
if (_index < 0 or _index >= array_length(_array)) {
return _default;
}
return _array[_index];
}
many array functions have been supporting negative values to dictate from the end of the array, as well as length to search, believe as GM heads in this direction all array functions should support the same when ever applicable. in the case for this it would only optionally take -1
meaning the last index, or -2
meaning the second to last index of the array.
Going off of Evan's suggestion (#59), if we want arrays to have similar helpers to structs, there's
struct_get
, which gets a value from a struct, defaulting toundefined
if it doesn't exist. I propose the same for arrays.Unfortunately, the name
array_get
is taken by a function that crashes on out-of-bounds, which is why I chosearray_get_or_undef
. I'm not particularly attached to that name, so feel free to suggest a better one.