Skip to main content

Quick start

Complete Settings → Install in Installation first, including after cloning the Demo. This tutorial verifies both call directions in the Editor; Player setup is covered in First Player build.

1. Create the C# entry point​

Save the following complete file as Assets/Bootstrap.cs. No scene component is needed; the initialization method runs automatically.

using System;
using System.IO;
using System.Text;
using UnityEngine;
using ZLua;

public static class Bootstrap
{
private static string LoadLuaModule(string module)
{
string relativePath = module.Replace('.', '/') + ".lua";
string path = Path.Combine(Application.dataPath, "..", "LuaScripts", relativePath);
if (!File.Exists(path))
{
throw new FileNotFoundException($"Lua module '{module}' not found", path);
}
return File.ReadAllText(path, Encoding.UTF8);
}

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void Initialize()
{
LuaAppDomain.Initialize(LoadLuaModule);
Action main = LuaAppDomain.GetFunction<Action>("app", "main");
Func<int, int, int> add = LuaAppDomain.GetFunction<Func<int, int, int>>("app", "add");
main();
Debug.Log($"Lua add: {add(10, 20)}");
}
}

Create Assets/Demo.cs:

public class Demo
{
public int x;

public static int Add(int a, int b) => a + b;
}

2. Create the Lua module​

Create LuaScripts/app.lua in the project root (LuaScripts is next to Assets):

local Demo = CSharp['Assembly-CSharp'].Demo

local function main()
local instance = Demo()
instance.x = 10
print("C# Add: " .. Demo.Add(3, 5))
print("C# field: " .. instance.x)
end

local function add(a, b)
return a + b
end

return { main = main, add = add }

GetFunction loads the module's returned table, resolves the function key, and returns a delegate. Lua uses CSharp[assemblyName] for types, a dot for static calls, and a colon for instance methods.

3. Verify​

Open any scene and enter Play mode. The Console should contain these lines in order:

C# Add: 8
C# field: 10
Lua add: 30

If the module is missing, check its file path. If Demo is missing, check the assembly name (asmdef projects must use their actual assembly name). Do not call Initialize again when a domain already exists; see LuaAppDomain.

Next​

Continue with First Il2Cpp Player build to add Player paths and resource loading. This tutorial's loader is Editor-only; on Android / WebGL, preload scripts with your project's resource system and supply them to the synchronous loader.

See Lua calling C# and C# calling Lua for daily use, or the complete zlua-demo project.