Alphish / gm-community-toolbox

A collection of utility functions for GameMaker.
MIT License
34 stars 6 forks source link

array_get_or_undef #60

Open Mercerenies opened 1 year ago

Mercerenies commented 1 year ago

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 to undefined if it doesn't exist. I propose the same for arrays.

function array_get_or_undef(array, index) {
  if ((index < 0) || (index >= array_length(array))) {
    return undefined;
  }
  return array[index];
}

Unfortunately, the name array_get is taken by a function that crashes on out-of-bounds, which is why I chose array_get_or_undef. I'm not particularly attached to that name, so feel free to suggest a better one.

gnysek commented 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];
}
tinkerer-red commented 11 months ago

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.