A demonstration of integrating Lua scripting into Unity using the MoonSharp interpreter for C# ↔ Lua interop.
This example shows how to call Lua functions from C#, expose C# functions to Lua, and share variables between the two languages using MoonSharp within Unity.
- Unity 2022.3 (works with 2018+)
- MoonSharp library
The example contains an update function written in Lua, which is called during Unity's Update method:
function update()
local currentTime = time() -- Get time from C# script
print('Time since startup: ' .. currentTime)
endIn C#, the Lua update function is fetched as a DynValue and then invoked during Unity's Update:
luaUpdateFunction = luaScript.Globals.Get("update");
if (luaUpdateFunction.Type == DataType.Function) {
luaScript.Call(luaUpdateFunction);
}Register C# functions to be callable from Lua:
luaScript.Globals["print"] = (Action<string>)LuaPrint;
luaScript.Globals["magnitude"] = (Func<float, float, float>)CalculateMagnitude;
luaScript.Globals["time"] = (Func<float>)GetTime;Retrieve values created in Lua scripts:
DynValue xValue = luaScript.Globals.Get("x");
Debug.Log("Getting variable x: " + xValue.Number);- Ensure Unity 2022.3 is installed
- Import MoonSharp library into your project
- Attach
LuaTest.csto any GameObject - Run the scene and check console for logs from both C# and Lua
Assets/
├── Scripts/
│ └── LuaTest.cs — Main C# script managing Lua interaction
├── Lua/
│ └── script.lua — Lua script with update function
└── README.md
- Initialize MoonSharp — Create a new Lua environment in C#
- Load Lua script — Execute Lua code from string or file
- Register callbacks — Expose C# functions to Lua via globals
- Retrieve functions — Get Lua functions as DynValue objects
- Call functions — Invoke Lua functions from C# with parameters
- Exchange data — Share variables between languages
DynValue function = lua.Globals.Get("functionName");
DynValue result = lua.Call(function, arg1, arg2);lua.Globals["methodName"] = (Func<int, int>)MyMethod;DynValue value = lua.Globals.Get("variableName");
int result = (int)value.Number;- Always wrap Lua execution in try-catch for error handling
- Ensure C# method signatures match expected Lua function calls
- Use DynValue for safe type conversion between C# and Lua
- Keep Lua scripts small and focused for better performance