Flash: Convert a function reference to a readable string
If you have a function reference in Flash there is not a lot of information you can get from it. Converting the function to a string will only give you:
1 | "function Function() {}" |
A describeType() wouldn’t give you more information either. Specially for debug purposes you would like to have some more information about the function, like his name or class.
By coincident I discovered that Flash throws an error if you try to cast a function to something else. The error message contains some more information about the function:
1 2 | "TypeError: Error #1034: Type Coercion failed: cannot convert MC{FunctionUtilsExample@2ac32e1 FunctionUtilsExample/myPrivateFunction()}@2ccbb21 to flash.utils.Dictionary.
at FunctionUtilsExample()" |
So a simple regular expression gave me the information I wanted. I created the following function in FunctionUtils for the Temple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public static function functionToString(func:Function):String { try { Dictionary(func); } catch (error:Error) { var regExp:RegExp = /MC{(?:.*) (.*)}/g; var s:String = String(regExp.exec(String(error.message))[1]); var i:int = s.indexOf("/"); var className:String = s.substr(0, i); var functionName:String = s.substr(i); functionName = functionName.substr(functionName.indexOf("::") + 2); if (Temple.displayFullPackageInToString || className.indexOf('::') == -1) { return className + "." + functionName; } else { return className.split('::')[1] + "." + functionName; } } return null; } |
Example:
1 | FunctionUtils.functionToString(new MovieClip().gotoAndPlay); |
returns
1 | "MovieClip.gotoAndPlay()" |
A lot more readable I think.
Unfortunately this only works in the Debug Player, but you should only use this for debug purposes.
Sources, including an example, is available from GoogleCode.