Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Integrate Lua with .Net

Tags:

c#

lua

Requirement is user should be able to add Lua script in text box, and then I need to check user has added proper Lua script and if script is correct then I need to run that script. Can anyone suggest me some code? I tried following:

    using (Lua state = new Lua())
    {
       state.DoString(txt.Text);            
       var scriptFunc = state["ScriptFunc"] as LuaFunction;
       var res = scriptFunc.Call(2,3);
       Response.Write(res);            
    }
like image 539
Urvi Avatar asked Mar 15 '23 11:03

Urvi


2 Answers

What you are looking for is Moon# (http://www.moonsharp.org/). So your example will look like this:

double MoonSharpFactorial2()
{
    string scriptCode = @"    
        -- defines a factorial function
        function fact (n)
            if (n == 0) then
                return 1
            else
                return n*fact(n - 1)
            end
        end";

    Script script = new Script();    
    script.DoString(scriptCode);

    DynValue res = script.Call(script.Globals["fact"], 4);

    return res.Number;
}
like image 53
aggsol Avatar answered Mar 23 '23 09:03

aggsol


From what I understand, you're trying to run Lua code within your C# application using the standard Lua API.

Unfortunately, this will not work, as standard Lua is written in C, which, while very similar to C# in it's structure, is not C# and is not compatible with the .NET framework.

Instead, you have to use a third-party wrapper such as NLua. ;)

like image 28
Radfordhound Avatar answered Mar 23 '23 09:03

Radfordhound