Lua 程序 ModLua program mods

用 Lua 在固定时机运行代码,通过 xLua 的 CS.* 访问游戏的 C# 对象。PC 与手机都会加载;手机上能调用哪些 C# API 有限制(见下文)。 Run Lua at fixed hooks and reach the game's C# objects through xLua's CS.*. Loads on PC and mobile; which C# APIs work on mobile is limited (see below).

声明入口Declaring the entry

<ModMetaVersion>
  <version>v_common</version>
  <luaMain>main.lua</luaMain>      <!-- 相对 v_common/Lua/relative to v_common/Lua/ -->
</ModMetaVersion>
ExampleLuaMod/
├─ Manifest/manifest.xml
└─ v_common/Lua/
   ├─ main.lua
   └─ helpers/defs.lua      ← require('helpers.defs')← require('helpers.defs')
  • 同一版本不能同时声明 luaMain 与 main/lib,也不能在 Assemblies/ 放 DLL。A version may not declare luaMain together with main/lib, nor ship DLLs in Assemblies/.
  • require 只接受点分模块名(字母、数字、下划线),只在本 Mod 的 Lua/ 目录内查找;找不到时才回退到 xLua 内置模块(如 xlua.util)。require accepts dotted names (letters, digits, underscore) and only searches this mod's Lua/ folder, falling back to xLua built-ins such as xlua.util.
  • 每个 Lua Mod 有独立的 LuaEnv,全局变量不会互相影响。Each Lua mod gets its own LuaEnv; globals don't leak between mods.

入口表与回调Entry table and callbacks

入口脚本必须 return 一个表:The entry script must return one table:

函数Function必需Required调用时机Called when
onLoad(ctx)✓Mod 安装时,游戏配置表尚未加载。适合注册事件。At install time, before game definitions load. Register events here.
onDefLoaded(ctx)所有原版行与 Mod XML 行已读入、尚未初始化和建立 ID 索引时。适合修改数据。After built-in and mod XML rows are read, before rows are initialised and indexed. Modify data here.
onUpdate(ctx, deltaTime)每帧,从 onDefLoaded 完成之后开始。不要每帧打印日志。Every frame, starting after onDefLoaded. Avoid per-frame logging.
onUnload(ctx)✓卸载或退出游戏时;加载中途失败时也会调用。必须撤销 onLoad 注册的所有事件,即使 onLoad 只执行了一半。On unload or quit, and also after a failed load. Must undo every subscription from onLoad, even if onLoad stopped halfway.

ctx 包含 packageId、version(选中的版本目录名)和 rootPath(本 Mod 的 Lua/ 目录绝对路径)。ctx has packageId, version (selected version folder) and rootPath (absolute path of this mod's Lua/ folder).

示例:修改原版数据Example: changing built-in data

完整文件在 examples/ExampleLuaMod/。它在 onDefLoaded 中把原版食物 ID 3 的价格翻倍;已在游戏中实测,日志输出 T_FoodDef 3 price 5.0 -> 10.0。Full files in examples/ExampleLuaMod/. It doubles the price of built-in food ID 3 in onDefLoaded; verified in game, logging T_FoodDef 3 price 5.0 -> 10.0.

v_common/Lua/main.lua
local defs = require('helpers.defs')
local TARGET_FOOD_ID = '3'

return {
    onLoad = function(ctx)
        print('[docs.example.lua] loaded, version=' .. ctx.version)
    end,

    onDefLoaded = function(ctx)
        -- beansDict / getDataID are not built yet here: iterate beans.
        local row = defs.findRow(CS.T_FoodDef.beans, TARGET_FOOD_ID)
        if row == nil then
            error('T_FoodDef ID=' .. TARGET_FOOD_ID .. ' not found')
        end
        row.Price = row.Price * 2
    end,

    onUnload = function(ctx) end
}
v_common/Lua/helpers/defs.lua
local M = {}
function M.findRow(beans, id)
    for i = 0, beans.Count - 1 do
        local row = beans[i]
        if row.ID == id then return row end
    end
    return nil
end
return M
为什么不用 CS.T_FoodDef.getDataID('3')? ID 索引在 onDefLoaded 之后才建立,此时调用会得到 nil。进入游戏后(例如在 onUpdate 中)就可以使用 getDataID。 Why not CS.T_FoodDef.getDataID('3')? The ID index is built after onDefLoaded, so it returns nil there. Once in game (e.g. in onUpdate) getDataID works.

订阅游戏事件Subscribing to game events

目前对 Mod 开放的 C# 事件只有建筑生成相关的 ModDelegateDispatch(见 API 参考)。返回 nil 表示不处理,交给下一个订阅者或游戏默认逻辑。The only C# events exposed to mods today are the building-generation hooks on ModDelegateDispatch (see the reference). Return nil to pass to the next subscriber or the default logic.

local handler = function(buildType, buildId, cellX, cellY, buildDir)
    return nil   -- or an FWBuildBean to take over creation
end

return {
    onLoad = function(ctx)
        CS.ModDelegateDispatch.generator_BuildBean('+', handler)
    end,
    onUnload = function(ctx)
        CS.ModDelegateDispatch.generator_BuildBean('-', handler)  -- same function object
    end
}

PC 与手机的差异(IL2CPP)PC vs mobile (IL2CPP)

PC 版运行在 Mono 上,xLua 可以通过反射访问几乎所有公开的 C# 类型。手机版是 IL2CPP:只有打包时生成了桥接代码、且没有被裁剪掉的类型才能可靠调用。当前生成配置如下(由导出器读取 ModLuaBindings 与 XLuaHotfixConfig): PC runs on Mono, where xLua can reach nearly any public C# type by reflection. Mobile is IL2CPP: only types with generated bridges that survived stripping are reliable. The current configuration (read from ModLuaBindings and XLuaHotfixConfig by the exporter):

  • 本页示例中的 CS.T_FoodDef.beans、字段读写和事件订阅已在编辑器(Mono)中实测可用;在手机正式包中是否可用尚未验证。The CS.T_FoodDef.beans access, field writes and event subscription on this page were tested in the editor (Mono); they have not been verified in a mobile release build.
  • 需要在手机上使用更多 API 时,请联系开发组把类型加入 ModLuaBindings 并重新打包。If you need more APIs on mobile, ask the developers to add the types to ModLuaBindings and rebuild.

出错时会怎样What happens on errors

  • 入口脚本或 onLoad 抛错:游戏先调用 onUnload 清理,该 Mod 不会安装;日志记录 Mod install failed: packageId=…,并弹出加载失败提示。选“继续”跳过它、接着加载后面的 Mod;选“清除所有MOD并重启”清空启用列表并重启游戏。Errors in the entry script or onLoad: the game calls onUnload to clean up and the mod is not installed; the log records Mod install failed: packageId=… and a load-failure prompt appears. “Continue” skips it and loads the remaining mods; “Clear all mods and restart” empties the enabled list and restarts the game.
  • onDefLoaded 抛错:配置表加载中止,加载画面停在“启动失败”,此时不会立即调用 onUnload。Errors in onDefLoaded: definition loading aborts and the loading screen shows the startup-failed message; onUnload is not called at that point.
  • 以上错误信息都包含 packageId、版本、入口文件和阶段 stage=。All of these messages include packageId, version, entry file and stage=.
  • onUpdate 抛错:记录一次错误,并停止该 Mod 之后的所有更新;游戏继续运行,不会每帧重试。Errors in onUpdate: logged once, and that mod receives no further updates; the game keeps running and does not retry every frame.
  • onUnload 抛错:该 Mod 的 Lua 环境被保留以便诊断,不会伪装成卸载成功。Errors in onUnload: the mod's Lua environment is kept for diagnosis instead of pretending the unload succeeded.

热修复(xlua.hotfix)Hotfix (xlua.hotfix)

用 xlua.hotfix 替换 C# 方法需要基础包启用 HOTFIX_ENABLE,且目标类型事先登记在 XLuaHotfixConfig 中(当前状态见上表)。多个 Mod 替换同一方法会互相覆盖,不是补丁链。普通 Lua Mod 不依赖此功能。 Replacing C# methods with xlua.hotfix needs a base build with HOTFIX_ENABLE and the target types pre-registered in XLuaHotfixConfig (current state above). Several mods patching one method overwrite each other — it is not a chain. Ordinary Lua mods don't need this.

运行时常用的游戏接口(配置表、文本、提示、日志、地图格、存档数据)和 Lua 调用 C# 的写法见常用游戏 API。由数据行触发的剧情脚本是另一套机制,见剧本 Mod。For the game interfaces used most at runtime (definitions, text, toasts, logging, map cells, save data) and how to call C# from Lua, see Common game APIs. Story scripts triggered by data rows are a separate mechanism; see Scenario mods.

Lua Mod 与 DLL Mod 一样是可执行代码,不是安全沙箱。Like DLL mods, Lua mods are executable code, not a sandbox.