Last active
August 29, 2015 14:01
-
-
Save SegFaultAX/629a3a8c15b0fd188000 to your computer and use it in GitHub Desktop.
Python -> Lua serialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SPECIAL_DELIM = [("[{}[".format("="*n), "]{}]".format("="*n)) for n in range(10)] | |
def type_of(v, *types): | |
return any(isinstance(v, t) for t in types) | |
def get_delim(s): | |
if '"' not in s: and "\n" not in s: | |
return ('"', '"') | |
for op, cl in SPECIAL_DELIM: | |
if op not in s and cl not in s: | |
return (op, cl) | |
raise ValueError("could not find delimiter for string") | |
def indent(s, level, prefix=" "): | |
return "\n".join("{}{}".format(prefix*level, l).rstrip() | |
for l in s.split("\n")) | |
def to_lua(v): | |
if type_of(v, str): | |
od, cd = get_delim(v) | |
temp = "{}{}{}".format(od, v, cd) | |
elif type_of(v, float, int): | |
temp = "{}".format(v) | |
elif type_of(v, dict): | |
kvs = [] | |
for k, v in v.iteritems(): | |
ks = "{}".format(to_lua(k)) | |
if ks.startswith("["): | |
ks = "[ {} ]".format(ks) | |
else: | |
ks = "[{}]".format(ks) | |
vs = to_lua(v) | |
kvs.append("{} = {}".format(ks, vs)) | |
temp = "{{\n{}\n}}".format(indent(",\n".join(kvs), 1)) | |
elif type_of(v, list, tuple, set): | |
kvs = [] | |
for i, v in enumerate(v): | |
ks = "[{}]".format(i+1) | |
vs = to_lua(v) | |
kvs.append("{} = {}".format(ks, vs)) | |
temp = "{{\n{}\n}}".format(indent(",\n".join(kvs), 1)) | |
else: | |
temp = to_lua(str(v)) | |
return temp | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
License on this?