Austin Salgat
Austin Salgat

Reputation: 415

How to dynamically generate functions?

I want to be able to take a string (with the proper Dart syntax) and convert it into a callable dart function. Is there a way to do that?

For example, I would receive the string,

void test() { print("testing!"); }

And then turn it into a callable function. The reason I want to do this is to be able to download dart files from other servers and call their functions.

Upvotes: 5

Views: 523

Answers (3)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657406

What you can currently do is create JavaScript and use it's eval() and use JS-interop.

Upvotes: 0

Fox32
Fox32

Reputation: 13560

Depends on your target platform. If you are targeting the standalone Dart VM, it is already possible. The SDK tool Pub is doing it.

You can setup a application internal webserver that serves your function embedded in a gernated application. Than you can load the application into a additional isolate and use message passing to communicate with that isolate. This approach can also be used to create plugins for our application.

But it may take much time to implement this on your own. If you want to parse mathematic expression or other simplified sub parts of the language, you might look into the available Pub packages (parsers or math_exprerssions).

Upvotes: 1

Bandrami
Bandrami

Reputation: 4542

Per the dart FAQ, https://www.dartlang.org/support/faq.html#q-is-it-really-a-dynamic-language-if-it-doesnt-have-eval-or-adding-fields-to-a-value-at-run-time

Dart does not currently have an eval() function, nor support runtime compilation of arbitrary strings, though it may in the future.

So, you'll have to make your own VM within dart to do what you want to do.

Upvotes: 2

Related Questions