如何从.NET调用Lua函数

时间:2010-03-26 21:12:36

标签: c# .net lua luainterface lua.net

我使用LuaInterface库来运行.net中的lua,它运行正常。我可以通过lua访问CLR。但是如何从C#调用Lua函数?

2 个答案:

答案 0 :(得分:2)

您需要获得LuaFunction的引用,您可以使用Call()函数。

示例代码可在this website上找到。

似乎在过去3年左右的时间里,LuaInterface已经变得不那么流行并且支持度较低。

无论如何,here's a newer link to a Channel 9 blog post that has some sample code

答案 1 :(得分:0)

有些照片在接受的答案中被打破,所以我决定添加新答案。

此解决方案要求您首先将NLua NuGet安装到您的项目中。 让我们说,我们需要得到一些表,或者只是总结两个变量。 您的Test.lua文件将包含:

-- Function sums up two variables
function SumUp(a, b)
    return a + b;
end

function GetTable()
    local table =
    {
        FirstName = "Howard",
        LastName = "Wolowitz",
        Degree = "just an Engineer :)",
        Age = 28
    };

    return table;
end;

您的C#代码如下所示:

static void Main(string[] args)
    {
        try
        {
            Lua lua = new Lua();
            lua.DoFile(@"D:\Samples\Test.lua");

            // SumUp(a, b)
            var result = lua.DoString("return SumUp(1, 2)");
            Console.WriteLine("1 + 2 = " + result.First().ToString());

            // GetTable()           
            var objects = lua.DoString("return GetTable()"); // Array of objects
            foreach (LuaTable table in objects)
                foreach (KeyValuePair<object, object> i in table)
                    Console.WriteLine($"{i.Key.ToString()}: {i.Value.ToString()}");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.ToString());
        }
        Console.WriteLine("Press any key...");
        Console.ReadKey();
    }