PDA

View Full Version : How to do enums in AS3



jackskelyton
May 10th, 2008, 01:46 PM
From what I can gather looking online and trying different things, there seems to be a couple of ways to solve the problem of using enum statements in AS3.

First, simply define a whole list of public static const ints at the top of an actionscript file, preferably the one using the enum constants most often. For example:

ActionScript Code:

public class Thingy

public static const ENUM_1:int = 1;
public static const ENUM_2:int = 2;
public static const ENUM_3:int = 4;

private var mType:int;

public function Thingy(type:int = 0) {

mType = type;

}




Then, when you make a new Thingy that needs to have reference an enumerated constant, you can just do:

ActionScript Code:

var thingy:Thingy = new Thingy(Thingy.ENUM_1);




Alternatively, you can make an "empty" class that just holds constant ints and import it to use in your other classes. This might be better for long lists of constants, and especially if you plan to do bitfield comparisons.

ActionScript Code:

public class Enums {

public static const ENUM_1:int = 1;
public static const ENUM_2:int = 2;
public static const ENUM_3:int = 4;
/* etc etc */
}




And then just use it where you need it, setting up your classes to receive int data as types or whatnot:

ActionScript Code:

var thingy:Thingy = new Thingy(Enums.ENUM_1);
if (thingy.type == Enums.ENUM_1) {
trace("good to go");
}




That's the way I see it, and it seems to do fine for my code. Does anyone know of a better way? I'd love to hear it if you do.

Krilnon
May 10th, 2008, 02:04 PM
The built-in classes use strings instead of integers, but other than that they are the same as what you mentioned above. The advantage I can see for using strings over integers is that you can trace them. (Event.ENTER_FRAME is 'enterFrame', etc.) With integers, you can or different enums together, though, so I think that either could be useful in some situations.

srivello
August 11th, 2009, 08:17 PM
Enums are my favorite community developed language feature!!!

An Enum is a kind of variable that is not natively available in ActionScript 3.0, but can be found in other languages such as C++. An enum is a type with a restricted set of values.

Here is a demo;
http://www.blog.rivello.org/?p=621