ZLua 的最小可运行示例:演示 C# → Lua(LuaAppDomain.GetFunction<T>)与 Lua → C#(CSharp 懒加载),无需 per-type C# Wrap 白名单。
- 文档:doc.zlua.cn
- 包仓库:zlua
- English:README_EN.md
| 项 | 说明 |
|---|---|
| Unity | 2022.3 LTS(本工程为 2022.3.62f3) |
| Lua | 随 ZLua 包内置(默认 5.4) |
| ZLua 包 | Packages/manifest.json 中 com.code-philosophy.zlua |
- Clone 本仓库(并按上一节准备好 ZLua 包依赖)。
- 用 Unity 2022.3 打开工程根目录。
- 打开场景并 Play(或直接 Play 默认场景)。
- 查看 Console:应出现
lua main start、各test_*日志,以及AppAdd(10,20)=30。
无需配置 LuaCallCSharp、无需为每个类型 Generate C# Wrap。
zlua-demo/
├── Assets/
│ ├── Bootstrap.cs # 初始化 + GetFunction 调 Lua
│ ├── Demo.cs # 供 Lua 访问的示例 C# 类型
│ └── Editor/
│ └── SyncLuaScriptsToStreamingAssets.cs # Player 构建前同步 Lua
├── LuaScripts/
│ └── app.lua # Editor 下直接加载的 Lua 模块
├── StreamingAssets/ # 构建时生成(*.lua.txt)
│ └── LuaScripts/
└── Packages/
└── manifest.json
| 路径 | 作用 |
|---|---|
LuaScripts/*.lua |
Editor 开发时的 Lua 源文件 |
StreamingAssets/LuaScripts/*.lua.txt |
Player 运行时读取(.txt 避免 Unity 导入规则冲突) |
Bootstrap 在场景加载前注册模块加载器并初始化 ZLua:
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void InitZLuaOnStartup()
{
LuaAppDomain.Initialize(LoadLuaModule);
}- Editor:从项目根
LuaScripts/{module}.lua读源码 - Player:从
StreamingAssets/LuaScripts/{module}.lua.txt读源码
用 GetFunction<T> 按模块名与方法名绑定 Delegate(须在 Initialize 之后,如 Awake):
Action AppMain;
Func<int, int, int> AppAdd;
void Awake()
{
AppMain = LuaAppDomain.GetFunction<Action>("app", "main");
AppAdd = LuaAppDomain.GetFunction<Func<int, int, int>>("app", "add");
}
void Start()
{
AppMain();
Debug.Log($"AppAdd(10,20)={AppAdd(10, 20)}");
}对应 LuaScripts/app.lua 中 return { main = main, add = add }。
Demo.cs 为普通 public 类型,无需导出配置。Lua 中:
CSharp['AC'] = CSharp['Assembly-CSharp']
print(CSharp.AC.Demo.Add(3, 5)) -- 静态方法
local d = CSharp.AC.Demo() -- 构造
d.x = 10 -- 字段
d:SetX(20) -- 实例方法app.lua 里的 test_* 函数在 main 中依次调用,覆盖静态 / 实例方法与字段访问。重载示例 test_overload_signature 默认注释,需要时可取消注释。
| 目标 | 做法 |
|---|---|
| 改 Lua 逻辑 | 编辑 LuaScripts/app.lua,Editor 下 Play 即生效 |
| 新增 C# API | 在 Demo.cs(或新脚本)写 public 成员,Lua 用 CSharp.AC.类型名 访问 |
| 新增 C#→Lua 入口 | LuaAppDomain.GetFunction<T>("模块", "函数"),并在对应 Lua return 表导出同名函数 |
| 新增 Lua 模块 | 在 LuaScripts/ 增加 {name}.lua,Loader 按模块名加载 |
含 namespace 的类型请用括号键,例如:CSharp.AC['MyGame.UI.Panel']。
- 菜单
ZLua/Generate/All(生成 C++ stub,不是 xLua 式 C# Wrap)。 - 确认 Lua 已同步到 StreamingAssets:
- 菜单 Tools → Sync LuaScripts To StreamingAssets,或
- 直接 Build(
IPreprocessBuildWithReport会自动同步)。
- Build Settings → 选择 IL2CPP → Build。
| 现象 | 处理 |
|---|---|
| Package 拉取失败 | 检查网络 / Git;或临时改为本地 "file:../../zlua" / "file:com.code-philosophy.zlua" |
module 'app' not found |
确认 LuaScripts/app.lua 存在;Player 需先 Sync |
Demo 为 nil |
程序集别名应为 CSharp.AC → Assembly-CSharp;类型须为 public |
| Player 无 Lua 输出 | 未 Generate,或未同步 StreamingAssets/LuaScripts/*.lua.txt |
与 ZLua 一致,采用 MIT。