|
What is the correct way to declare and use a enum variable, in Javascript?
(comments are locked)
|
|
Like this (using the example of various AI states for an AI State Machine):
And then you can assign any value from that enum to a variable, like this:
In the above example, the variable's type is implicitly defined as "AIState". You can explicitly define a variable with that type like this:
And similarly you can define the input parameter of a function to recieve a value from your enum, like this: I've upvoted your answer because it helped me, but your example code is slightly incorrect. In the enum declaration, you've named it 'Asleep', but in the switch, you're checking for 'Sleeping'. Cheers.
Jun 15 '10 at 08:55 AM
Marowi
thanks for the pointer! just edited it to fix that.
Jun 15 '10 at 10:10 PM
duck ♦♦
Is it true that enum declarations have to be outside of a function?
May 18 '11 at 11:51 PM
RoxPhilosopher
(comments are locked)
|
|
You can also assign values to your individual enum elements.
This is incredibly helpful if you use layers, for example. Rather than using
You could instead use the easier to read
This is especially helpful as there is then only one location, your enum, where you have to change the layer number if a change is needed. What would be the purpose of assigning them different layers? Is it one way to have another kind of differentiation? Such as only finding objects within a certain layer?
Oct 12 '11 at 11:00 PM
sabliao
(comments are locked)
|

Can you comment on whether (1) the enum declaration and (2) the use of the variable, has to be in the (a) the same script, (b) a script on the same object or (c) doesn't matter?
To keep things organised I have all my enums in their own scripts in a separate folder (Scripts/Enums). If your enums are within a class you'll have to specify the class prior to the enum to access it, which is often needlessly awkward.
Is enum limited to integer-values? This site here states that the sub-vars of an enum-declaration are always integer. I need float - is there a way?
Positive integers, actually... it's one of the limitations of enums.
Exactly. If you use the enum as a variable type, the variable is actually just an int32 behind the scenes. This is a fix behaviour and can't be changed.
You can use an enum + an array with float values and use the enum constants as index into the array to get the float value.