python 表 转 lua table 字符串

python 表 转 lua table 字符串

      • 0. 特性:
      • 1. 直接上代码
      • 2. 用法
      • 3. 实例
        • 3.1 代码
        • 3.2 输出

前言: 有个给cocos2dx-lua 写工具的需求, 要求导出lua table文件,找不到现成合用的库,于是自己写了一套

0. 特性:

  1. list dict tuple 可混合使用 统一转换成 lua的table
  2. 带有合理的缩进
  3. 引用成环 会报错
  4. key只能为字符串或数字

1. 直接上代码

class LuaMaker:
    """
    lua 处理器
    """

    @staticmethod
    def makeLuaTable(table):
        """
        table 转换为 lua table 字符串
        """
        _tableMask = {}
        _keyMask = {}
        def analysisTable(_table, _indent, _parent):
            if isinstance(_table, tuple):
                _table = list(_table)
            if isinstance(_table, list):
                _table = dict(zip(range(1, len(_table) + 1), _table))
            if isinstance(_table, dict):

                if _tableMask.has_key(id(_table)):
                    print("error: LuaMaker.makeLuaTable() 成环: this = "+ _parent + "  oldP = " + _tableMask[id(_table)])
                    return

                _tableMask[id(_table)] = _parent
                cell = []
                thisIndent = _indent + "    "
                for k in _table:
                    if not (isinstance(k, str) or isinstance(k, int) or isinstance(k, float)):
                        print("error: LuaMaker.makeLuaTable() key类型错误: parent = "+ _parent + "  key = " + k)
                        return
                    key = isinstance(k, int) and "[" + str(k) + "]" or "[\"" + str(k) + "\"]"
                    if _keyMask.has_key(_parent + key):
                        print("error: LuaMaker.makeLuaTable() 重复key: key = "+ _parent + key)
                        return
                    _keyMask[_parent + key] = True

                    var = None
                    v = _table[k]
                    if isinstance(v, str):
                        var = "\"" + v + "\""
                    elif isinstance(v, bool):
                        var = v and "true" or "false"
                    elif isinstance(v, int) or isinstance(v, float):
                        var = str(v)
                    else:
                        var = analysisTable(v, thisIndent, _parent + key)
                    cell.append(thisIndent + key + " = " + var)
                lineJoin = ",\n"
                return "{\n" + lineJoin.join(cell) + "\n" + _indent +"}"

            else:
                print("error: LuaMaker.makeLuaTable() table类型错误: "+ _parent)

        return analysisTable(table, "", "root")
        

2. 用法

strLuaTable = LuaMaker.makeLuaTable(tableTTT)

3. 实例

3.1 代码

tableTTT = {
    1:456,
    2.3:"2dsfaads",
    "ks":("fsda","eqwe"),
    "list":[13,"fdsa"],
    "d":{"a":456}
    }
ttt = LuaMaker.makeLuaTable(tableTTT)
print(ttt)

3.2 输出

{
    ["ks"] = {
        [1] = "fsda",
        [2] = "eqwe"
    },
    [1] = 456,
    ["list"] = {
        [1] = 13,
        [2] = "fdsa"
    },
    ["d"] = {
        ["a"] = 456
    },
    ["2.3"] = "2dsfaads"
}

你可能感兴趣的:(python 表 转 lua table 字符串)