alternative for switch statement?

Hi all,

I'm a MS BC14 user and there is this way of checking for certain values IN a variable

Example:
IF variable IN [0, 5, 12, 50, 16] THEN BEGIN ... END;

I know I can do this with a switch statement but it seems so much trouble just to check for certain numeric values.. and I rather not use the && because it could get really long..

So I was wondering if there was something similar I'm not aware of to the example for game maker?
 

chamaeleon

Member
No there is no built-in way of doing this.

The following works but it's of course inefficient to create the set every loop (it is just a simple example)
GML:
function set() {
    var result = {};
    for (var i = 0; i < argument_count; i++) {
        result[$ argument[i]] = 1;
    }
    return result;
}

for (var i = 0; i < 10; i++) {
    if (!is_undefined(set(1, 3, 5, 7, 9)[$ i])) {
        show_debug_message("Found " + string(i));
    }
}
Code:
Found 1
Found 3
Found 5
Found 7
Found 9
If the set can be created a priori and reused over and over (like in the case of a static set like your example), one can of course store it at game start in a global variable.

Or, given Frostycat's warning about not testing against undefined since it is a valid value for a struct member (although it may not necessarily be an issue when you create static sets using numbers, etc.)
GML:
for (var i = 0; i < 10; i++) {
    if (variable_struct_exists(set(1, 3, 5, 7, 9), i)) {
        show_debug_message("Found " + string(i));
    }
}
 
Last edited:

YellowAfterlife

ᴏɴʟɪɴᴇ ᴍᴜʟᴛɪᴘʟᴀʏᴇʀ
Forum Staff
Moderator
Easier solution:
Code:
/// @param value
/// @param ...options
function is_either() {
    var v = argument[0], i = 0;
    repeat (argument_count - 1) {
        if (argument[++i] == v) return true;
    }
    return false;
}
and then:
Code:
if is_either(variable,  0, 5, 12, 50, 16) ...
 

Nidoking

Member
searching something is always faster than creating copy of something, searching it and destroying
This is a true statement. I don't see why you've chosen to quote what I said while making this completely separate statement that has nothing to do with what I said.
 
Top