• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

GameMaker Best way to iterate in an enum?

M

MagnumVulcanos

Guest
The question is self explanatory, I want to do something for every value in an enum.
Sadly enums aren't lists, and there's no java-like method like the following:
Code:
for ( value in enum ) {
  do thing with value
}
My current solution is this:
Code:
enum gases { carbon_dioxide, oxygen, nitrogen }
global.gases_listed = ds_list_create();
global.gases_listed[|0] = gases.carbon_dioxide;
global.gases_listed[|1] = gases.oxygen;
global.gases_listed[|2] = gases.nitrogen;
And when I do need to use them and do somthing for each of them, I just use the list for it. Am I missing a function that returns all values in an enum?
 
Last edited by a moderator:

Binsk

Member
Use something other than an enum.

Enums are just convenient macros that don't exist post compile (and thus aren't actually a structure of any kind).

Since enums are just integers and, assuming you leave their values at defaults, you could just loop through an integer list from 0 to the number of enum values.

If you don't leave the values at default then there is no clean way to loop through them all.
 
M

Marcus12321

Guest
What I usually do with my enums is let them count from 0 like normal, and the last item in the list is called length.

Then when I want to run through them as a list, I can just do a repeat (enums.length). And it will run the loop (or whatever) the number of times as the number of items in the enum.
 

FrostyCat

Redemption Seeker
One common workaround for enums without explicit values is to include a length entry at the end:
Code:
enum EXAMPLE {
  VALUE_A,
  VALUE_B,
  VALUE_C
  length
}
Then the following would run through each value in order:
Code:
for (var i = 0; i < EXAMPLE.length; i++) {
  //...
}
 
Top