using NLua; using System; // Create a new Lua state Lua lua = new Lua(); // Define a Lua function to add two numbers lua.DoString(@" function add(x, y) return x + y end "); // Call the Lua function from C# double result = (double) lua.DoString("return add(2,3)")[0]; Console.WriteLine(result); // Output: 5
using NLua; using System; // Create a new Lua state Lua lua = new Lua(); // Define a C# class public class Calculator { public int Add(int x, int y) { return x + y; } } // Register the C# class with Lua lua["calculator"] = new Calculator(); // Call the C# method from Lua script int result = (int) lua.DoString("return calculator:Add(2,3)")[0]; Console.WriteLine(result); // Output: 5In this example, we create a new Lua state and define a C# class called Calculator with an Add method. We then register the Calculator class with Lua and call the Add method from a Lua script. Finally, we print the result. Package library: NLua provides access to the .NET Framework from Lua scripts, allowing the use of .NET classes and libraries.