python - 将 dict 序列化为 lua 表

标签 python python-3.x lua

Converting .lua table to a python dictionary查询将 lua 表转换为可以使用 loadstring/loadfile 加载的 python 字典。 answer's建议使用一个库,它也支持相反的转换,但它不再维护也不支持 python3。

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

最佳答案

我最终自己实现了它:

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)}")

关于python - 将 dict 序列化为 lua 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54392760/

相关文章:

python - 在 pandas for python 中创建虚拟变量

python - 使用Python上传多个Web文件到云存储

python - 为 pandas 数据框的分组列绘制一列差异图

python - 将列表的元素添加到字典中的固定位置

lua - 如何使用 Lua 脚本在 Redis 中传递换行符

将 Lua 脚本编译为 unsigned char 缓冲区

oop - 为什么.__index只返回子类的函数而不返回基类的函数

Python 2.7 Tkinter : How would I config the shape under the mouse with key press

python - 使用字典映射数据帧索引

python - 如何将给定数据框的索引和列名称一起列出?