GMLscripts.com

Discuss and collaborate on GML scripts
Invert

You are not logged in.

#1 2018-01-29 17:44:48

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

is_in

It's just silly but saves me a lot of time; mostly posting to remind everyone that we can do this: Basically, comparing multiple variables to one value.

Expand///	@description		Returns whether a value is in the supplied set of arguments
///	@function			is_in( value, test0, [test1], [...] )
///	@param				value	The value to search for
///	@param				test0	Value to compare to
///	@param				[test1]	Add parameters as needed to extend the set
///	@returns	{bool}	True when value was found in set
/*
*	Suppose we want to test whether x, y, or z is equal to value.
*	GameMaker:
*		if(x==value || y==value || z==value)
*	Python:
*		if value in {x, y, z}
*	This script shortens what you'd have to type in GameMaker like so:
*		if is_in(value, x, y, z)
*		Also accepts an array: 
*			array = [x, y, z];
*			if is_in(value, array)
*/
// Created for SLIDGE engine
// GMLscripts.com/license

var test = argument[0];
var argz = 0;
for(var z=1; z<argument_count; z+=1){
	argz = argument[z];
	if(is_array(argz)){
		for(var i=0; i<array_length_1d(argz); i+=1){
			if(test == argz[i]){
				return true;
			}
		}
	}else{
		if(test == argument[z]){
			return true;
		}
	}
}
return false;

Have fun saving keystrokes; feel free to balloon this out to test data type mismatches and all manner of other fun things as needed.

Last edited by Tsa05 (2018-06-24 17:44:13)

Offline

#2 2018-01-30 08:26:14

gnysek
Member
Registered: 2011-12-29
Posts: 36

Re: is_in

should be rather:

Expand/*		if is_in(value, x, y, z)
*/

as in GMS2 you can again use variable_exists functions, in which case "variableName" would suggest you need to pass a string.

Last edited by gnysek (2018-01-30 08:26:26)

Offline

#3 2018-01-30 09:15:52

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

Re: is_in

Ahhhh. Took me a moment to realize what you meant; absolutely right. I put variableName in the explanation comment in order to illustrate the difference in what gets typed into your code in comparison to how you'd have to type it without the script. But to anyone who's not me, it looks like the example of the function "in use" requires a string with the variable name due to my naming schema... Adjusting now for clarity!

Offline

#4 2018-01-31 13:01:23

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

Re: is_in

Nice! Good solution to a common problem. Nothing silly about it. Thanks!


Abusing forum power since 1986.

Offline

#5 2018-06-24 17:43:14

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

Re: is_in

Just added a small update to the script, so that it takes in an array *or* list of arguments. This way, you can build a set of test values instead of hard-coding the names to test against.

Offline

Board footer

Powered by FluxBB