Or, “Hack Your Stack for Fun and Profit!” Yes, this is really and truly a hack, my friends, but, like many hacks, you might find it very useful. Using the Stack class I provide, you can get all sorts of information about the code being run right now: the package, class name, method, filename, and even the line number. You can also grab an Array version of a stack trace and follow it up. Sweet!
So check out this egregious hack. First, you grab the stack trace by throwing and catching a dummy Error and copping its stack trace as a string. Note, that this technique only works (and is only useful) in the Debug Player.
public static function getRawStackTrace():String
{
var stackTrace:String;
try
{
throw new Error();
} catch (error:Error) {
stackTrace = error.getStackTrace();
}
return stackTrace;
}
Then you slice it up into lines, and hack those lines into their constituent parts by some crazy regular expressions. That’s pretty much it.
public static function getPartsFromStackTraceEntry(stackEntry:String):Object
{
return stackEntry.match(/(?P<package>[\w\d\.]+)::(?P<classname>[\w\d\.\:]*?)(?P<isStatic>\$?)\/((?P<scope>[\w\d\.\:]+)::)?(?P<method>[\w\d]+\(\))(\[(?P<filename>[\w\d\\\/\.]+):(?P<line>\d+)\])?/);
}
Fun, right? The properties in the returned Object are:
- package
- classname
- isStatic
- scope
- method
- filename
- line
You can clean this up into package.classname::method with getSimplifiedStackTraceEntry().
So that’s it, it’s just some regular expressions, but with this hack you can pull out all kinds of juicy information about the context your code is running in. It can be useful for your own debugging, logging, and error reporting.
com.yourmajesty.debug.Stack View Source | Download (.as, 2k)