Reputation: 481
Converting .lua table to a python dictionary inquires about converting a lua table to a python dict that can be loaded with loadstring/loadfile. The answer's suggested a library which also supports conversion the other way around, however it is no longer maintained nor supported python3.
I was unable to find a piece of code that does this conversion anywhere.
Upvotes: 1
Views: 1178
Reputation: 481
I ended up implementing it by myself:
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)}")
Upvotes: 2