This example demonstrates how to integrate Lua scripting into a Unity project using the MoonSharp interpreter. The provided LuaTest.cs
MonoBehaviour showcases the basics of how to call Lua functions from C#, expose C# methods to Lua, and access Lua variables from C#.
- Tested with Unity 2022.3. Should work with Unity 2018 and above.
- MoonSharp library (which serves as the Lua script engine)
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)
end
In 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);
}
C# functions can be registered with the Lua environment to make them callable from Lua scripts. In the provided example:
LuaPrint allows Lua to log messages to the Unity console. CalculateMagnitude computes the magnitude given two float arguments. GetTime fetches the time since the application started.
luaScript.Globals["print"] = (Action<string>)LuaPrint;
luaScript.Globals["magnitude"] = (Func<float, float, float>)CalculateMagnitude;
luaScript.Globals["time"] = (Func<float>)GetTime;
Accessing Lua Variables from C# Lua variables can be accessed from C# after they've been defined in the Lua environment. For instance, after defining x in Lua, it's fetched in C# as follows:
DynValue xValue = luaScript.Globals.Get("x");
Debug.Log("Getting variable x from state: " + xValue.Number);
- Ensure you have Unity 2022.3 installed.
- Import the MoonSharp library into your Unity project.
- The LuaTest monobehaviour is attached to the camera in the example code. Attach it to any game object.
- Run the scene. Observe the Unity console for messages logged from both C# and Lua.
- Important Notes
- Always wrap your DoString calls with a try-catch to handle any Lua runtime errors gracefully.
- Ensure that the C# methods you expose to Lua have the correct signature to match the expected Lua function calls.