views:

249

answers:

2

Is there a way to define an enum in AS3 in a way we do it in other languages? I can define constants with defined values like that:

private const CONST_1:int = 0;
private const CONST_2:int = 1;
private const CONST_3:int = 2;

and so on. If I want to insert some other constant between 3 these I need to move all values like that:

private const CONST_1:int = 0;
private const CONST_2:int = 1;
private const CONST_2A:int = 2;
private const CONST_3:int = 3;

while in other language I would end up with only adding a new member to enum closure like that:

enum {
    CONST_1 = 0,
    CONST_2,
    CONST_2A,
    CONST_3
} MyConstEnum;

Does AS3 has something similar?

Thanks

+4  A: 

No AS3 doesn't have enum, you have to code them yourself. You can simulate them for example by a class if you want safer type checking :

Patrick
I like the Scott Bilas method.
Heath Hunnicutt
+2  A: 

You can take a look at the variety of variable types supported by the ActionScript Virtual Machine. Variable types are annotated by traits, the variety of which can be found in the specification, table 4.8.1:

4.8.1 Summary of trait types
The following table summarizes the trait types.

Type           Value
Trait_Slot       0
Trait_Method     1
Trait_Getter     2
Trait_Setter     3
Trait_Class      4
Trait_Function   5
Trait_Const      6

There is no Trait_Enum and note that under Trait_Const description, only constants from the constant pool are allowed, so that would be:

  • signed integers
  • unsigned integers
  • doubles
  • strings
  • type names and vector types

Enums could be made of signed or unsigned integers, for example, but the virtual machine would not perform any type-safety checking of the operations which used those types. (E.g., the getlocal or coerce opcodes used would be getlocal_i and coerce_i, respectively.)

The ABC format doesn't have any built-in provision for enum types that I know of.

Using an object type for each enum value could work, especially if the compiler emits coerce instructions for that type prior to uses of getlocal and otherwise doesn't use the object other than in istype and astype variants. For example, calling setproperty or getproperty on the object would be slower than using an integer -- especially if that property is bound to a getter or setter method.

There are replacement styles which have been linked in other answers. To evaluate the runtime performance impact of these styles, you can uses swfdump -D from the swftoools open-source Flash tools collection.

Heath Hunnicutt
Thank you for detailed explanation.
Nava Carmon