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#?
Asked
Active
Viewed 7,218 times
2
-
Maybe you have same problem as me [same problem][1] [1]: http://stackoverflow.com/questions/6856826/c-external-library-lua-call-problem – Riadh Abdelhedi Jul 28 '11 at 18:43
2 Answers
2
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.

Charlie Salts
- 13,109
- 7
- 49
- 78
-
1Lua l = new Lua(); l.DoFile("log.lua"); LuaFunction f = _LuaTestManager["log_info"] as LuaFunction; if (f != null) f.Call("My log message"); Made it. Thanks – Mar 26 '10 at 21:22
-
@SteveFolly I've edited my comment. It's been a long while since I've worked with Lua in C# and as I state in my comment, it seems to have become a bit less popular. The LuaInterface seems to not be too active. – Charlie Salts Nov 20 '13 at 02:35
-
2
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();
}

Erik BRB
- 215
- 6
- 19