Thursday 17 September 2009

Command Engine


The CommandEngine class contains the core of my command console. It is basically a simple script interpreter, which can execute methods and read/write properties. Methods can be nested, and can return any type and have any parameters.

You can make a static property or method available to the engine by sticking the [Command] attribute onto it. The engine will scan the assembly and pick out all these methods and properties.

[Command]
public static string Print(object o)
{
    var s = o.ToString();
    Debug.WriteLine(s);
    return s;
}


[Command]
public static string Hellp { get; set; }


[Command]
public static int Framerate
{
    get { return fpsCounter.Value; }
}

Adding instance methods and properties has to be done by calling the AddCommand or AddOption method on the engine instance respectively.

engine.AddOption(player, "Position", "Player.Position");


[Command]
public static Vector3 Vector3(float x, float y, float z) 
{ return new Vector3(x, y, z); }

Once you have some commands registered, you can call them with the execute method:

engine.Execute("Print("Testing"));
engine.Execute("Print(Framerate)")
var helloString = engine.Execute("Hello").Result;
engine.Execute("Player.Position = Vector3(0, 10, 3)");


You can download the source here.

No comments:

Post a Comment