Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert string to code at run time

I am generating strings containing if else expressions. I was wondering if I can execute this expressions at run time? Here's an example:

string s = "if(x > 10) {Fly = true;} else {Fly = False;}";
Execute (s); 

Is it even possible to do this?

like image 578
Hani Goc Avatar asked Sep 12 '13 13:09

Hani Goc


3 Answers

It is possible to use TCC ( http://bellard.org/tcc/ ). It allows to compile and run code natively at runtime. Another approach is to use an interpreter, there are plenty out there (LUA, Python etc, see list wiki).

like image 184
Raxvan Avatar answered Sep 23 '22 16:09

Raxvan


One does not simply interpret C/C++ code... AFAIK you just can't.
(except if you compile another binary and run it from cmd line maybe...)

Note: You can write

fly = (x > 10);

instead of

if(x > 10){
    fly = true;
}else{
    fly = false;
}
like image 36
johan d Avatar answered Sep 20 '22 16:09

johan d


No. C++ is a compiled language and has no eval-function or the-like. You may want to include a scripting engine into your program, like Lua

like image 33
Constantin Berhard Avatar answered Sep 24 '22 16:09

Constantin Berhard