使用 xres-code-generator 生成读表代码
xres-code-generator 基于 Mako 模板引擎,可读取 xresloader 导出的 .pb 描述文件并生成各语言的读表逻辑。
- 转表工具仓库:https://github.com/xresloader/xresloader
- 读表代码生成工具仓库:https://github.com/xresloader/xres-code-generator
建议先完成 快速上手,确认生成 bin 与 descriptor。本文示例使用 .bytes 后缀,文件路径需与实际输出统一。
正式项目最推荐用生成器加载配置并按索引读表。 C++ 和原生 Lua 的简短查询示例见 推荐加载方式。
公共前置步骤
引入扩展声明
所有需要生成读表代码的 .proto 必须 import "xrescode_extensions_v3.proto" 并在消息级别设置 option (xrescode.loader)(文件位于 xres-code-generator/pb_extension/):
syntax = "proto3";
import "xrescode_extensions_v3.proto";
message role_upgrade_cfg {
option (xrescode.loader) = {
file_path : "role_upgrade_cfg.bytes"
indexes : {
fields : "Id"
index_type : EN_INDEX_KL // Key-List 索引
}
indexes : {
fields : "Id"
fields : "Level"
index_type : EN_INDEX_KV // Key-Value 索引
}
tags : "client"
tags : "server"
};
uint32 Id = 1;
uint32 Level = 2;
uint32 CostType = 3;
int32 CostValue = 4;
int32 ScoreAdd = 5;
}
生成 .pb 描述文件
REPO_DIR=$PATH_TO_xres_code_generator
PROTOC_BIN="$(which protoc)"
"$PROTOC_BIN" \
-I "$REPO_DIR/sample/proto" \
-I "$REPO_DIR/pb_extension" \
--include_imports \
"$REPO_DIR/sample/proto/"*.proto \
-o "$REPO_DIR/sample/sample.pb"
上游 sample/proto 中包含 pb_header_v3.proto。自己的工程也要将该包装头纳入 descriptor,连同加载选项及其依赖一起交给生成器;仅含业务消息的入门 kind.pb 不能直接替代这一步。
xrescode-gen.py 常用参数
-i:模板根目录(通常为xres-code-generator/template)-p:输入的.pb描述文件-o:输出目录-g/-l/-f:指定模板与输出路径,-f prefix:template:relative_output可精确控制文件名--set key=value:向模板注入自定义变量--add-path dir:扩展模板搜索路径
如需一次生成全部示例,可执行 xres-code-generator/sample/sample_gen.sh,脚本会:
- 复制各语言运行时依赖;
- 调用
tools/find_protoc.py自动选择protoc; - 针对 C++、UE、Lua(多实现)与 C# 执行
xrescode-gen.py; - 生成
main.cpp、main.lua等示例入口。
语言与生态
每种语言/生态的详细命令与接口说明已拆分为独立文档,可按需查阅:
- C++(原生工程)
- Unreal Engine / Blueprint
- Lua(原生 table)
- C# / Unity
- Lua(upb 运行时)
- Lua(lua-protobuf 运行时)
- Golang
自定义模板与扩展
官方模板位于 xres-code-generator/template。可通过以下方式扩展:
- 复制现有模板并根据项目需求改写;
- 使用
--set传入定制变量; - 通过
--add-path指定额外的模板目录。
在 CI/CD 流程中,可在 xresloader 导出阶段直接调用 xrescode-gen.py,让转换出的数据、descriptor 与读表代码使用同一份协议。数据后缀由项目决定,本站入门示例使用 .bin。