Wiki
Clone wikidsair / BitFlag
#HOWTO: BitFlag: Using the BitFlag class to keep state #
Introduction
This class is a copy of the BitFlag class on my site: http://divillysausages.com/blog/a_bitflag_class_for_as3
If you don't know what a bit flag is, check out http://en.wikipedia.org/wiki/Bit_field
Details
Check out the TestBitFlag.as file for the full details.
As with all examples, you need to init the framework before doing anything:
#!actionscript DSAir.init( this ); // "this" is your Document class
BitFlags
can be created with an optional class to check our flags against. This is useful if you want to make sure that your BitFlag
can only have a specific set of flags. If you wish to do this, pass the class in the constructor:
#!actionscript var flag:BitFlag = new BitFlag( MyFlags );
##Adding flags##
You can add single flags by:
#!actionscript flag.addFlag( 1 << 1 );
or multiple:
#!actionscript flag.addFlags( 1 << 2, 1 << 3, 1 << 4 );
##Removing flags##
#!actionscript flag.removeFlag( 1 << 1 );
or multiple:
#!actionscript flag.removeFlags( 1 << 2, 1 << 3, 1 << 4 );
##Toggling flags##
Toggling a flag will add it if it's not there, and remove it if it is:
#!actionscript flag.toggleFlag( 1 << 1 );
or multiple:
#!actionscript flag.toggleFlags( 1 << 2, 1 << 3, 1 << 4 );
##Checking for flags##
You can check if your BitFlag
has a specific flag set by using:
#!actionscript flag.hasFlag( 1 << 1 );
or multiple:
#!actionscript flag.hasFlags( 1 << 1, 1 << 2 )
By default, hasFlags()
checks for all the flags. If one of the flags passed isn't present, then the whole function returns false
. If you want to check for the presence of any of the flags, call:
#!actionscript flag.hasAnyFlag( 1 << 1, 1 << 2 )
##Using a custom flag class##
If you want to use a custom class so your BitFlag
can only have specific flags added to it, you can pass the class into the constructor. The class is vetted for valid flags. For example, if we had a class like this:
#!actionscript internal class MyFlags { public static const ONE:int = 1 << 1; public static const TWO:uint = 1 << 2; public static const IGNORED_STRING:String = "random"; public static const IGNORED_INT:int = 25; public static const IGNORED_NUMBER:Number = 1.0; public static const TOO_LARGE:int = 1 << 31; }
then only ONE
and TWO
will be considered valid flags. IGNORED_STRING
is ignored because it's a String, IGNORED_INT
is ignored because it's not a flag, IGNORED_NUMBER
is ignored because it's not an int or an uint, while TOO_LARGE
is ignored as it's too big (you can only have 30 flags in a single BitFlag
).
If you create a BitFlag
with a flag class, then any of the calls to it's functions will first pass through a check function to see if they're alright.
Updated