Mircea
Mircea

Reputation: 31

C# execut a function created from string

I'm trying to make like a small interpreter from some scripting language to C# and I need to execute a C# method which is written in a string variable and I want to execute that. Is that possible? And if yes... how exactly can I do this?

My functions function on the end will look something like this:

 public IEnumerator Blink()
    {
        TurnOnLed(true);
        yield return new WaitForSeconds(2);
        for (var i = 0; i < 10; ++i)
        {
            TurnOnLed(false);
            yield return new WaitForSeconds(1);
            TurnOnLed(true);
            yield return new WaitForSeconds(1);
        }
    }

Script code:

output(true)
sleep(2)
for x in range(10)
    output(false)
    sleep(1)
    output(true)
    sleep(1)

Where WaitForSeconds is a Unity3D function and TurnOnLed(true) it's mine. when I seach on internet I've fond some solutions where I will create an entire class to be able to run this methon... is any other solution?

Is it there any easy way to do this?

Upvotes: 0

Views: 212

Answers (2)

Nat Ng
Nat Ng

Reputation: 81

Given that you're using Unity, there's a cheap and slightly hacky way to do this: The built-in Unity function GameObject.SendMessage() allows you to invoke C# functions using the function name string. Here's the relevant code from the Unity docs:

public class ExampleClass : MonoBehaviour {

    void ApplyDamage(float damage) {
        print(damage);
    }

    void Example() {
        gameObject.SendMessage("ApplyDamage", 5.0F);
    }

}

Hope this helps.

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

You really have to create complete classes to be able to run resulting C# code. You can always wrap code fragment into class with single method to construct a working class and than compile it (compiling covered in Is it possible to dynamically compile and execute C# code fragments? )

var myCode = "Console.WriteLine(\"!!!\")";
var classFormat = "class Fake{0} {{ public void Do(){{ {1} ;}} }}";
var finalCode = String.Format(classFormat, 123, myCode);

It sounds like you actually want to build code to run rather than transcode your script into C#, than compile C# into IL and than execute IL. Instead you can directly generate IL or construct Expression tree - starting points Reflection.Emit vs CodeDOM. Based on your script sample and requirement to not create complete classes Expression tree would be better option.


Another option is to use existing scripting engines - Lua, JavaScript, Python and many other have parsers that allow you to execute scripts from .Net code (i.e. How can I call (Iron)Python code from a C# app?)

Upvotes: 1

Related Questions