2

I use the LuaInterface library to run the lua in .net and it works fine. I could access the CLR via lua. But how to call Lua function from C#?

4

2 回答 2

2

您需要获取对 a 的引用LuaFunction,从中可以使用 Call() 函数。

示例代码可以在这个网站上找到。

似乎在过去 3 年左右的时间里,LuaInterface 变得有点不那么流行和支持了。

无论如何,这里有一个更新的链接,指向包含一些示例代码的 Channel 9 博客文章

于 2010-03-26T21:21:22.757 回答
1

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

此解决方案要求您首先将 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();
    }
于 2018-05-29T10:10:17.070 回答