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#?
2 Answers
You'll need to get a reference to a LuaFunction, from which you can use the Call() function.
Sample code can be found on this website.
It seems that in the last 3 years or so, LuaInterface has become a bit less popular and less supported.
In any case, here's a newer link to a Channel 9 blog post that has some sample code.
3 Comments
Some of the pictures are broken in accepted answer, so I decided to add new answer.
This solution requires you to install NLua NuGet to your project first. Let's say, that we need to get some table, or just sum up two variables. Your Test.lua file will contain:
-- 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;
Your C# code will look like:
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();
}