A handy little function (GML)

Posted by Gift of Death on March 23, 2017, 11:22 a.m.

As far as I know GML is silly and doesn't have a built in function to check if a value is smaller or greater than all of a given set of numbers. I mean there are situation where you can use min() and max() functions but there are situations where they don't work. It would make your if-statements a little more readable and easier to manage at times.

So yeah, it's dangerous to go without, here. *shoves them into your face*

smallerThan( real, array[val1, val2…] )

/// @description		Checks if a number is smaller than all of a set of given numbers
/// @param real			Value to compare
/// @param arr[val1		Array of values to compare against, can also given as single parameters (val1, val2, val3...)
/// @param val2...]

var _c = argument[0];

if( argument_count == 2 ) {
	var _vals = argument[1];
	
	for( var i = 0; i < array_length_1d(_vals); i++ ) {
		if( _c > _vals[i] ) {
			return false;
		}
	}
}else{
	for( var i = 1; i < argument_count; i++ ) {
		if( _c > argument[i] ) {
			return false;
		}
	}
}

return true;

greaterThan( real, array[val1, val2…] )

/// @description		Checks if a number is greater than all of a set of given numbers
/// @param real			Value to compare
/// @param arr[val1		Array of values to compare against, can also given as single parameters (val1, val2, val3...)
/// @param val2...]

var _c = argument[0];

if( argument_count == 2 ) {
	var _vals = argument[1];
	
	for( var i = 0; i < array_length_1d(_vals); i++ ) {
		if( _c < _vals[i] ) {
			return false;
		}
	}
}else{
	for( var i = 1; i < argument_count; i++ ) {
		if( _c < argument[i] ) {
			return false;
		}
	}
}

return true;

Could've made them into a single script that can be flipped between smaller and greater check by a bool but I sort of prefer having 2 separate ones. It's a bit clearer in my opinion.

// Okay here's one more for finding if a value is contained in a set of values, works in a similar way.

contains(real, array[val1, val2…])

/// @description		Checks if an array or a set of values contains the compared value
/// @param real			Value to compare
/// @param arr[val1		Values to compare against, can also be an array of values
/// @param val2...]

var _c = argument[0];

if( argument_count == 2 ) {
	var _vals = argument[1];
	
	for( var i = 0; i < array_length_1d(_vals); i++ ) {
		if( _c == _vals[i] ) {
			return true;
		}
	}
}else{
	for( var i = 1; i < argument_count; i++ ) {
		if( _c == argument[i] ) {
			return true;
		}
	}
}

return false;

Comments