View Single Post
Codemonkey's Avatar Codemonkey Codemonkey is online now Super Moderator 2006-11-25 #35 Old  
032 - Calling methods with eval()
 
You can't dynamically call functions with eval() like in Javascript or PHP unless you create your own parser for it, as well as for assignments etc. Flash can only locate identifiers for you with eval and that isn't necessary anymore these days.

If you want a quick way to call certain functions using a string, here's one way to do that (in AS2 at least):

ActionScript Code:
  1. // some values and a user function we'll call
  2. var monkeys:String = "monkeys!";
  3. var apes:String = "apes!";
  4.  
  5. function myFunc(str1:String, str2:String) {
  6.     trace(str1 + " and " + str2);
  7. }
  8.  
  9. // locate a function and apply the arguments to it
  10. function parseFunction(s:String) {
  11.     var fname:String = s.split("(")[0];
  12.     var parameters:String = s.split(")")[0].substr(fname.length + 1);
  13.     var paramlist:Array = parameters.split(", ");
  14.    
  15.     // get the results of each argument
  16.     for (i in paramlist) {
  17.         paramlist[i] = eval(paramlist[i]);
  18.     }
  19.     // call the function with the specified arguments
  20.     var func:Function = eval(fname);
  21.     func.apply(this, paramlist);
  22. }
  23.  
  24. // try to call user function, and a system function
  25. parseFunction("myFunc(monkeys, apes);");
  26. monkeys = "three little monkeys";
  27. parseFunction("trace(monkeys);");
You could expand it to parse expressions as well and execute several commands by splitting the string with ';'.