How to Integrate Lua with .Net

14,281

Solution 1

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;
}

Solution 2

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. ;)

Share:
14,281
Urvi
Author by

Urvi

Updated on June 04, 2022

Comments

  • Urvi
    Urvi almost 2 years

    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);            
        }