Numeric Enumerations (Enums) for AS3
Posted in Methodology, Programming, Tips on April 14th, 2010 by ManuelSomething I really missed in Actionscript 3 were enums. If you need ascending unique numeric ids ( e.g. for naming array indexes ), enums are your friend.
For our current project we programmed a messaging system. The system uses unique numeric ids for message types and message channels. The list of messages and channels grew over time and right now each list contains more than a hundred entries. In the beginning we did the numbering ourselves like that:
public static const MSG_OPEN_WINDOW:int = 0;
public static const MSG_CLOSE_WINDOW:int = 1;
public static const MSG_REGISTER_TIMER:int = 2;
// .. and so on
For code beauty we were always trying to group related message ids, which often meant to re-index dozens of entries if we inserted an id somewhere in between. This was a pain!
The net already has assembled quiet some wisdom about “fake enums ins as3″¹, which do fit different needs (like some have type safety) but unfortunately not ours. Most of them are String based, which is what we did not want. So after putting in some thought we came up with a solution that worked for us. Now we can define our enums like this:
public static const MSG_OPEN_WINDOW:int = cEnum.Enum(0);
public static const MSG_CLOSE_WINDOW:int = cEnum.inc;
public static const MSG_REGISTER_TIMER:int = cEnum.inc;
// .. and so on
Now, by using static methods and a static counter we can create an arbitrary amount of coherent numeric values, which comes in very handy from time to time! Re-indexing is in the past now!
We want to share our little enum class with the web, so here it comes:
public class cEnum
{
private static var m_currentIncrement:int = 0;
/**
* Adds an enum value to the collection
*/
public static function Enum(_v:int) : int
{
m_currentIncrement = _v;
return m_currentIncrement;
}
/**
* returns the next increment
*/
public static function get inc():int
{
return ++m_currentIncrement;
}
}
Bottom line, if you need a neat way to maintain a list of static coherent numeric entries while type safety is not a big issue … this is an fairly easy way to do it. May this help you out there as much as it helped us.
Have fun and happy coding
Manuel
¹ Further readings on AS3 enums can be found here: e.g. http://www.herrodius.com/blog/87,
http://scottbilas.com/blog/faking-enums-in-as3/
or http://blog.petermolgaard.com/2008/11/02/actionscript-3-enums/
Popularity: 31% [?]

