Pre-Processing ActionScript files / classes
One thing I often do in my code is create custom trace / output functions that recursively go through and print out properties. However, this requires that I add some custom code to my classes which I don’t really want in the final version.
So, I started exploring pre-processors that I could use to make it easier to add and remove debugging code. I first looked at m4. While it seems to be very powerful, it was overkill for what I needed, and looked to be very difficult to use. Christian Cantrell then suggested that I look at cpp, a C pre-processor. I checked it out, and it does exactly what I need, in an easy to learn and use syntax.
For example, here is a simple class, in a file call HelloWorld.p
class HelloWorld
{
function HelloWorld()
{
#ifdef DEBUG
trace("Hello World Loaded");
#endif
}
}</pre>
#ifdef is a cpp directive that is basically an if statement. If the DEBUG variable is defined, then the block will be included in the generated file, if not, then it will be omitted.
I then run this file through cpp like so:
cpp -D DEBUG -P HelloWorld.p HelloWorld.as
The -D DEBUG defines the DEBUG variable. -P tells cpp to not insert line-markers in the generated file. You have to use this for ActionScript or else Flash won’t compile your file. (You can find a completel list of command-line args here).
Running this results in the following HellowWorld.as file:
class HelloWorld
{
function HelloWorld()
{
trace("Hello World Loaded");
}
}
Running it without defining DEBUG:
cpp -P HelloWorld.p HelloWorld.as
results in the following file:
class HelloWorld
{
function HelloWorld()
{
}
}
With the trace statement removed.
Note that by default, cpp will remove any comments from the generated AS file. If you want it to keep the comments in the file, just add -C to the argumenst that you pass to cpp
Anyways, this is just a simple example. There are a ton of directives you can use, and you can also define your own.
The main thing that you have to remember is that you must run your class file through cpp before it is compiled by Flash. Flash is compiling the file generated by cpp, and not the file you are editing.
You can find more info on cpp here, and you can download it from here (it is included with the GCC compiler).
Note, cpp is included on Mac OS X, but for some reason would not work for me. I had to download the source, and compile it before I could get it to work. If anyone can get it to work on Mac, let me know in the comments.
Post any additional tips / uses of cpp with ActionScript, or suggestions in the comments.