Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# scripting without hardcoding

I am trying to create a game with scripting in C#. I asked a similar question earlier but the example pointed to invovled hardcoding in the .cs file. Is there anyway to compile and run an Assembly containing C# code that contains functions, assignments, operators and types that can change variables in the hosting .cs file? For example:

my .cs file contains a string variable myName.
my script code contains a function myfunction.
Is there any way to access myName from my function and change its value in my .cs file just by calling the Invoke method on myfunction? Without hardcoding myfunction in my .cs file?

like image 460
Anoop Alex Avatar asked Dec 20 '22 21:12

Anoop Alex


1 Answers

NLua can do pretty much what you want and it's extremely easy to implement it into your project.

Lua lua = new Lua();
lua.DoString("return 'Hello World!'");

You can also register DotNet functions for use in your script files.

lua.RegisterFunction("print", this, typeof(Program).Print("Print"));

After that you can use it in your .lua file file like that:

function Run()
    print("Hello World!")
end

And one more example specifically for what you're planning to do. So lets say you have Actor class:

class Actor
{
    public string name;
    public int age;
}

This is how we introduce our DotNet stuff to scripting:

Lua lua = new Lua();
lua["actor"] = new Actor();

And now in the script:

function Run()
    actor.name = "Thomas"   
    actor.age = 20
end

I used global variable in this example, so instance of Actor class will be accessible in all scripts. This is how we can pass it as a function argument:

Lua lua = new Lua();
lua.LoadFile("Script.lua");
LuaFunction function = lua["Run"] as LuaFunction;
function.Call(new Actor());
like image 57
martynaspikunas Avatar answered Dec 22 '22 11:12

martynaspikunas