Skip to main content
February 25, 2011
Answered

Dynamic Function Calling

  • February 25, 2011
  • 1 reply
  • 1703 views

I am attempting to dynamically populate a function at runtime and then have the ability to call this function. Anybody know how this could be done?

This topic has been closed for replies.
Correct answer Kenneth Kawamoto

What you need is eval(). Unfortunately eval() is not available in AS3, although it is defined in ECMA script standard. (It was in AS1/2.)

Fortunately, there are some very clever people who produced their own implementations I will use D.eval by RIA 1 here. http://www.riaone.com/products/deval/

Let's say you have this XML:

<function name="exampleFunction" arg0="num:int" arg1="str:String" returns="String">return num + str</function>

First you have to convert it to a string in AS3 Function format:

function exampleFunction(num:int, str:String):String{return num + str};

Then evaluate it as Function, and execute it.

...

import r1.deval.D;

...

var xml:XML = <function name="exampleFunction" arg0="num:int" arg1="str:String" returns="String">return num + str</function>;
var functionString:String = "function " + xml.@name + "(" + xml.@arg0 + ", " + xml.@arg1 + "):" + xml.@returns + "{" + xml + "};";
var dynamicFunction:Object = D.parseFunctions(functionString);
trace(D.eval("exampleFunction(3, ' spacemen');", null, dynamicFunction));

Traces

3 spacemen

1 reply

Adobe Expert
February 25, 2011

Depends on what you mean by that but you can do things like:

var someFunction:Function = function(arg0:uint, arg1:uint):uint {return arg0 + arg1};
trace(someFunction(3, 6));
February 25, 2011

This is almost what I meant, I guess I should have went into more detail (sorry about that), I want to be able to read the contents of an XML file, then dynamically read a function child(<function arg0="int:Num" arg1="String:str" returns="type">function body</function>) then make a Function object out of it which can be called by Actionscript later. I am familiar with the XML classes within Flash, and I know how to parse most primitve data types, but I can't think of how to do make a function body out of a string.

Participating Frequently
February 25, 2011

There is no way to do that And is not the best to do so anyhow.  This would be a pain to debug by any developer.

All things dynamic must have rules and structure to enable it.

Therefore anything you are trying to achieve with xml can be achieved by passing parameters in flash.

you can use the function arguments  or ... rest behavior or even :* for unknown types to pass in or return.