• 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!

Get the number of elements in an enum

E

Emily

Guest
How can I return the number of elements created by an enum?
I want to get 3 in the following cases.

enum states {idle, move, attack}
 

FoxyOfJungle

Kazan Games
As far as I know it is not possible, instead you can use a variable or in the enum itself to insert the number of items.

GML:
enum player_state
{
    idle,
    move,
    atack,
}

state_count = 2; //number of entries (from 0)
Remembering that the enum entries are just numbers/integers and cannot be changed at runtime.
 
Last edited:
The way I do it is add num to the end of each enum:
Code:
enum player_states {
   JUMP,
   CLIMB,
   IDLE,
   WALK,
   NUM
}
So that way the number of elements is player_states.NUM-1. Looping through all the elements is:
Code:
for (var i=0;i<player_states.NUM;i++) {
   // Do something with state i here
}
 
E

Emily

Guest
> RefresherTowel
Thank you
I will also try that method
Enum is very convenient and nice
 
D

Deleted member 45063

Guest
I also use the method @RefresherTowel mentioned, I'd just like to state that for readability you might want to define that last element as something like length rather the uppercase version so you can visually distinguish it from the regular enum constants, or the reverse if your enum constants are lowercase
 
Last edited by a moderator:

chamaeleon

Member
Just want to mention adding a "count" entry at the end only makes sense if you let the enums have 0 through n-1 values and you're not using the ability to assign arbitrary values to the enum entries, like 1,2,4,8,16 (not uncommon for bit flags, etc.) In such a scenario you will need to keep track of if some other way independent of the enum.
 
Top