How do I iterate over an enum in Haxe?
Asked Answered
P

1

15

I have an enumerator type:

enum PlayerProps {
    Attempts;
    Gold;
    Diamonds;
}

What should I do to iterate through all enum values? Something like:

var props = new Map<PlayerProps, Int>();
for (prop in PlayerProps)
    props[prop] = 0;
Presidentelect answered 19/3, 2014 at 19:56 Comment(0)
D
19

What you are looking for is Type.allEnums():

for (prop in Type.allEnums(PlayerProps))

Working example on try.haxe.org.

Distaste answered 19/3, 2014 at 20:23 Comment(4)
Thanks, I've found allEnums a bit later too. But now I have learned that Map can't use enum type as a key...Presidentelect
Oh, my bad for not testing that, I think you could find a workaround by using the int-value of the enum (it should be accessible somehow) but I guess that is not the best solution for this. Have you considered creating an object instead of a map? You could define a class that as a field for each property (this may or may not work for your needs)Distaste
I'm trying to find workaround with IntMap and Type.enumIndex method. But this looks quite clumsy.Presidentelect
@Presidentelect Enums in maps should work, they should use: haxe.ds.EnumValueMap. If you have issues try type it as var mProps:EnumValueMap<PlayerProps,Int> = new EnumValueMap() and see if that makes a difference...Genuine

© 2022 - 2024 — McMap. All rights reserved.