Copy link to clipboard
Copied
Hello,
Is it possible to convert a string to a new function e.g.
var myNewFunction:Function;
myNewFunction = "myStringFunction(){trace('this has been called');};"
myNewFunction();
//trace Result
this has been called
Thanks in advance
Copy link to clipboard
Copied
Copy link to clipboard
Copied
Hi,
Thanks for the link but this highlights something I already know, Im afraid.
My actual problem is that I want to create a new function using the string passed.
e.g.
var myNewFunction:String = "myStringFunction(){trace('this has been called');};"
and then call that function
myNewFunction()
Which will then call the trace command within the string:
"trace('this has been called')" which is found withing the string passed.
The problem with the example you gave is that the function being called has already been declared elsewhere within the file so it would be just a case of calling that function via a string. As illustrated in your link.
I want to actually create a new function "on the fly" that has not been declared anywhere, other than within the string being passed.
Thanks again for your help though.
Copy link to clipboard
Copied
This is not possible in AS3 unless you parse the string and create function as a property of a dynamic object. Unlike in JavaScript there is no analogue to eval().
Copy link to clipboard
Copied
hmmmmmm, that is annoying. But thank you for your help.
Copy link to clipboard
Copied
I don't think this is annoying. I personally prefer it this way. I would go even further stating that if AS3 had this capacity I would hate it. AS3 is a strictly typed language with a high level of security.
This is in addition to the fact that there is nothing you cannot do with AS3 in terms of creating dynamic objects. There are much better and, most importantly, most efficient ways to deal with functionality your original question describes. eval() or similar capacity would a big setback.
If you describe what you need to accomplish in more general terms - there may be useful suggestions from other developers. I mean, why evaluating string into an Object has particular appeal to you?
Find more inspiration, events, and resources on the new Adobe Community
Explore Now