Posted 23 March 2014 - 10:35 PM
So, I realize dumping a PHP array to JSON and then decoding the JSON in ComputerCraft is not the most efficient way to send data from a server to ComputerCraft. Because of that, I wrote this simple function to serialize a PHP array to a format that textutils.unseralize can handle. It will output it in the same exact format as textutils.seralize.
EDIT: PYTHON!
function serialize_to_lua($data) {
$lua_table = "{";
foreach ($data as $index => $value) {
$lua_table .= (is_numeric($index) ? "[".$index."]=" : "[\"".$index."\"]=");
if (is_array($value)) {
$lua_table .= serialize_to_lua($value);
}
else if (is_bool($value)) {
$lua_table .= ($value ? "true" : "false");
}
else if (is_numeric($value)) {
$lua_table .= $value;
}
else {
$lua_table .= "\"".$value."\"";
}
$lua_table .= ",";
}
$lua_table .= "}";
return $lua_table;
}
EDIT: PYTHON!
def serialize_to_lua(data):
def serialize(key, value):
lua_table = (("["+str(key)+"]=") if isinstance(key, int) else ("[\"" + str(key) + "\"]="))
if (isinstance(value, (list, dict))):
lua_table += recursion(value)
elif (isinstance(value, bool)):
lua_table += (("true") if value else ("false"))
elif (isinstance(value, int)):
lua_table += str(value)
else:
lua_table += "\"" + str(value) + "\""
lua_table += ","
return lua_table
def recursion(data):
lua_table = "{"
if (isinstance(data, dict)):
for key, value in data.iteritems():
lua_table += serialize(key, value)
else:
for index, value in enumerate(data):
lua_table += serialize(index, value)
lua_table += "}"
return lua_table
return recursion(data)
Edited on 07 July 2014 - 05:34 PM