GMLscripts.com

Discuss and collaborate on GML scripts
Invert

You are not logged in.

#1 2019-02-09 17:14:08

Tsa05
Member
Registered: 2016-11-16
Posts: 13

is_between(test, min, max); The one we do every day

Couldn't find on the search, but since we test things between a range a million times a day, why not scriptify it?

///	@description	Returns whether a test value is between 2 other values
///	@arg	{real}	test		The value to test
///	@arg	{real}	minimum		The low value in the range
///	@arg	{real}	maximum		The high value in the range
///	@arg	{bool}	*Inclusive	Include min and max in the check
///	@returns	{bool}	Whether the test value is between the min and max
/*
*	Simply turns the all-too-common check into a single plain-English command. Inclusive flag optional
*	Also works with inverted ranges, eg the min is really the max 
*	and the max is really the min. This saves the trouble of needing
*	to pre-sort the values before testing.
*/
var test = argument[0];
var low = argument[1];
var hig = argument[2];
var inc = false;
if(argument_count>3){
	inc = argument[3];
}
if(inc){
	if( (test>=low && test<=hig) || (test<=low && test>=hig) ){
		return true;
	}else{ return false; }
}else{
	if( (test>low && test<hig) || (test<low && test>hig) ){
		return true;
	}else{ return false; }
}

Offline

#2 2019-02-09 22:35:08

xot
Administrator
Registered: 2007-08-18
Posts: 1,201

Re: is_between(test, min, max); The one we do every day

This logic could be tightened up a little bit:

if  (inc) {
    return (test>=low && test<=hig) || (test<=low && test>=hig);
} else {
    return (test>low && test<hig) || (test<low && test>hig);
}

An inclusive test could even be done this way:

//  Inclusive
return test == median(test,low,hig);

But the median() function would not handle strings as well as comparisons do.


Abusing forum power since 1986.

Offline

#3 2019-02-09 23:16:45

Tsa05
Member
Registered: 2016-11-16
Posts: 13

Re: is_between(test, min, max); The one we do every day

Fair enough biggrin  I was going for legibility with the if-else structure, but it probably does add execution time!

The use of median is clever!--though I wanted a solution that could be inclusive or exclusive, thanks to the ambiguity of the English language biggrin

Offline

#4 2019-02-09 23:46:07

xot
Administrator
Registered: 2007-08-18
Posts: 1,201

Re: is_between(test, min, max); The one we do every day

It's your prerogative to use:

if (condition) {
    return true;
} else {
    return false;
}

... but you must accept that many people on Teh Internets will want to punch you for it.


Abusing forum power since 1986.

Offline

Board footer

Powered by FluxBB