Automatic conditional debug/release execution in ActionScript 3 (Flex 3)

Hi, this time I'll show you how to automatically detect if you Flash has been compiled in debug or release mode.

What's this all about?

I don't know if someone else did this (sorry if it's the case) but I just figured out a way to automatically detect if the Flex 3 (AS3) application has been compiled in debug or release mode, without having to change a single line on your source code.

This comes from the fact that Flex 3 doesn't have a native pre-compiler and not even a _DEBUG global constant to be able to know how it was compiled.
I used to make a global constant myself but a lot of times forgot to change it, having debug info on release mode or debugging a Flash to later find out it did absolutely no traces whatsoever Y_Y.

Well, there's actually a hackish way to know: The Call stack. If you used Flash for a while you would know that there's a difference in the call stack when we are on release mode: No file or line information is showed.
Luckily for us, the Error class has a way to get the call stack string.
So throwing a bogus error, catching it and checking it against a regular expression will give us the information we wanted: Are we in debug mode or not?

Source code

Add this two files to you project root, and call Debug.initialize() somewhere. Then you'll be able to use the _DEBUG boolean anywhere on your code to check for compilation mode.

_DEBUG.as

// Copyright (C) 2009 - Martín Sebastíán Wain - http://www.tbam.com.ar
// Shared under the MIT permissive licence. Please do not remove this comment.

package {
\tpublic var _DEBUG:Boolean = false;
}

Debug.as
// Copyright (C) 2009 - Martín Sebastíán Wain - http://www.tbam.com.ar
// Shared under the MIT permissive licence. Please do not remove this comment.

package {

\tpublic class Debug {
\t\t
\t\tstatic public function initialize():void {
\t\t\ttry {
\t\t\t\tthrow new Error("Intentional error to get call stack");
\t\t\t}
\t\t\tcatch(e:Error)
\t\t\t{
\t\t\t\t//Test the call stack for file/line info
\t\t\t\tvar re:RegExp = /\\[.*:[0-9]+\\]/;
\t\t\t\t_DEBUG = re.test(e.getStackTrace());
\t\t\t}
\t\t}
\t\t
\t}
\t
}

Usage example
if(_DEBUG)
\tplayer.health = 999999;
else
\tplayer.health = 100;\t

If you liked this tutorial, please link to it. I'll appreciate it.
Good luck with your projects!

-Martín

0 comments: