【发布时间】:2023-04-10 03:42:02
【问题描述】:
Converting .lua table to a python dictionary 询问如何将 lua 表转换为可以使用 loadstring/loadfile 加载的 python dict。 answer's 建议了一个也支持反向转换的库,但是它不再维护也不支持 python3。
我无法在任何地方找到可以进行这种转换的代码。
【问题讨论】:
标签: python python-3.x lua
Converting .lua table to a python dictionary 询问如何将 lua 表转换为可以使用 loadstring/loadfile 加载的 python dict。 answer's 建议了一个也支持反向转换的库,但是它不再维护也不支持 python3。
我无法在任何地方找到可以进行这种转换的代码。
【问题讨论】:
标签: python python-3.x lua
我最终自己实现了它:
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)}")
【讨论】: