将字典序列化为 Lua 表

将 .lua 表转换成 Python 字典 询问有关将 Lua 表转换成可以用 loadstring/loadfile 加载的 Python 字典的方式。答案 提供了一个支持双向转换的库,但它不再支持 Python3。

我无法在任何地方找到可以执行该转换的代码。

点赞
用户4356506
用户4356506

我最终自己实现了它:

def dump_lua(data):
    if type(data) is str:
        return f'"{re.escape(data)}"'
    if type(data) in (int, float):
        return f'{data}'
    if type(data) is bool:
        return data and "true" or "false"
    if type(data) is list:
        l = "{"
        l += ", ".join([dump_lua(item) for item in data])
        l += "}"
        return l
    if type(data) is dict:
        t = "{"
        t += ", ".join([f'[\"{re.escape(k)}\"]={dump_lua(v)}' for k,v in data.items()])
        t += "}"
        return t

    logging.error(f"Unknown type {type(data)}")
2019-01-27 20:51:29