Alphish / gm-community-toolbox

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

wrap() #23

Closed glebtsereteli closed 1 year ago

glebtsereteli commented 1 year ago

Description

Arguably one of my most commonly used functions - a way to wrap a value around a min-max range.

Definition

/// @func wrap()
/// @param {Real} value
/// @param {Real} min
/// @param {Real} max
/// @desc Returns the given value wrapped around the min-max range.
/// @returns {Real} 
function wrap(_value, _min, _max) {
    return ((_value > _max) ? _min : ((_value < _min) ? _max : _value));
}

Example

Cycling through any index-based storage system: inventory, menu items, etc.

var _input = ((keyboard_check_pressed(vk_down)) - (keyboard_check_pressed(vk_up)));
if (_input != 0) {
    index = wrap(index + _input, 0, amount - 1);
    item = items[index];
    // ...
}
Alphish commented 1 year ago

For your list-scrolling example, I'd typically use modulo function, especially now that eucmod is a thing (vide issue #4).

So the code rewritten would be like:

var _input = keyboard_check_pressed(vk-down) - keyboard_check_pressed(vk_up);
if (_input != 0) {
    index = eucmod(index + _input, amount);
    item = items[index];
    ...
}

So I don't personally find much use for the wrap function, especially when eucmod already exists (and even more so when wrap is a name that people might potentially want to use for other function/variable). ^^'

Mercerenies commented 1 year ago

I agree; this seems like the modulo function but with odd behavior when you try to scroll multiple at the same time. For instance, with the proposed implementation, wrap(6, 1, 4) would be 1, when it looks to me like we've scrolled two past the end and hence should be at 2. If we go forward with this, it should be implemented in terms of eucmod to handle multiple scrolls in one go, but again, I don't see the utility.

Alphish commented 1 year ago

Since no one seems to defend the separate wrap function, and the thread author reacted with thumbsup to my reply, I'm going to close this issue. If someone decides they really really really need such a function and eucmod won't cut it, I might reconsider (given a very real and sufficiently common scenario where hypothetical wrap function is preferable to eucmod).