serialize a dict as lua table

Question:

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.

Asked By: 0e1val

||

Answers:

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)}")
Answered By: 0e1val
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.