Skip to main content
Inspiring
April 29, 2014
Question

Create function from string????

  • April 29, 2014
  • 1 reply
  • 809 views

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

This topic has been closed for replies.

1 reply

Inspiring
April 29, 2014
DazFazAuthor
Inspiring
April 29, 2014

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.



Inspiring
April 30, 2014

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().