因为在游戏公司做 web 后台开发, 经常会涉及到取游戏服务器的数据库里面读写各种操作
昨天下午, 服务器那边让我读一个配置显示到后台, 让运营大佬们可以在 web 后台配置游戏参数
本来以为很简单个事情, 结果我读出那个二进制的字段, 居然是这种格式
{1=0,2=0,3=0,4=2,5={},6=0,7={1=118,s010GameConfig={s008wPayType=0,s009wCostType=0,s015dwReservedRule3=3,s015dwReservedRule2=0,s006ClubId=0,s010wCostValue=0,s010wCellScore=1,s014wPlayCountRule=10,s013wHadPlayCount=0,s010dwPlayRule=0,s010wSubGameID=114,s009wMaxScore=0,s015dwReservedRule1=0,s015sPrivateTableID=0}
服务器的兄弟告诉我, 这是 lua 的 table 很简单啦, 就这样(此处省略几百字)
然后我
然后我在网上搜索有么有前辈大佬留下的线程轮子结果不是要加载一个 lua vm 的虚拟机库就是各种麻烦还不知道能不能解决的一些方案
博主好歹也是有四年 + 工作经验的人了, 没有合适的就自己写嘛, 就当锻炼一下自己咯
新建一个项目, 取了一个好听的名字 SharpluaTable
- class SharpluaTable
- {
- string luatable = "";
- // 从{开始解析
- // 然后按等号分割, 等号前后为一个键值对
- // 逗号之后, 为另一个键值对
- // 如果遇到中途遇到 {, 一直解析到} 为止, 都为值
- Dictionary<string, string> dic = new Dictionary<string, string>();
- public Dictionary<string, string> Parse(string luatable)
- {
- this.luatable = luatable;
- // 解析 0 位和最后一位, 判断是否是 luatable 格式
- if (luatable[0] != '{')
- {
- throw new Exception("解析 lua 失败, 格式错误");
- }
- if (luatable[luatable.Length - 1] != '}')
- {
- throw new Exception("解析 lua 失败, 格式错误");
- }
- string luaKey = string.Empty, LuaValue = string.Empty;
- // 标示解析 Key 还是 Value, 如果 true, 那么解析到 Key 里面, 如果是 false, 那么解析到 value 里面
- bool iskey = true;
- for (int i = 1; i < luatable.Length; i++)
- {
- // 如果是逗号, 那么存储当前的 key value , 跳过当前字符解析
- if (luatable[i] == ',')
- {
- dic.Add(luaKey, LuaValue);
- luaKey = string.Empty;
- LuaValue = string.Empty;
- iskey = true; // 跳过一个逗号, 那么继续解析为 key
- continue;
- }
- else
- {
- if (luatable[i] == '=')
- {
- iskey = false; // 如果是等号, 那么解析为 key, 并跳过当前
- continue;
- }
- // 如果是二级的 {, 那么解析到} 为止, 并把当前的 i 的值移动到}的下标位置
- if (luatable[i] == '{')
- {
- //LuaValue += luatable[i];
- int kuohaoCount = 0;
- for (int j = i; j < luatable.Length; j++)
- {
- LuaValue += luatable[j];
- if (luatable[j]=='{')
- {
- kuohaoCount += 1;
- }
- if (luatable[j]=='}')
- {
- kuohaoCount -= 1;
- if (kuohaoCount==0)
- {
- i = j;
- break;
- }
- else
- {
- //kuohaoCount -= 1;
- }
- }
- }
- }
- else
- {
- if (iskey)
- {
- luaKey += luatable[i];
- }
- else
- {
- LuaValue += luatable[i];
- }
- }
- }
- }
- return dic;
- }
目前前这个解析类只做了一层解析, 如果 value 值有多层级, 我默认把它解析到 value 里面
测试一下
- string luatable = "{1=0,2=0,3=0,4=2,5={},6=0,7={1=118,s010GameConfig={s008wPayType=0,s009wCostType=0,s015dwReservedRule3=3,s015dwReservedRule2=0,s006ClubId=0,s010wCostValue=0,s010wCellScore=1,s014wPlayCountRule=10,s013wHadPlayCount=0,s010dwPlayRule=0,s010wSubGameID=114,s009wMaxScore=0,s015dwReservedRule1=0,s015sPrivateTableID=0},s006GameID=114},8=1}";
- SharpluaTable lua = new SharpluaTable();
- var dic = lua.Parse(luatable);
- Console.WriteLine(dic["7"]);
- SharpluaTable luaitem = new SharpluaTable();
- var items = luaitem.Parse(dic["7"]);
如果有多层级的, 那就再 new 一个 SharpLuaTable 对象, 再进行一次解析就好了
来源: https://www.cnblogs.com/boxrice/p/8512790.html