mudgangster

Log | Files | Refs

serialize.lua (1003B)


      1 -- can't handle cycles, only works on strings/numbers/bools/tables
      2 
      3 local function formatKey( key )
      4 	if type( key ) == "string" then
      5 		return "[ %q ]" % key
      6 	end
      7 
      8 	return "[ %s ]" % tostring( key )
      9 end
     10 
     11 local function serializeObject( obj )
     12 	local t = type( obj )
     13 
     14 	if t == "number" or t == "boolean" then
     15 		return tostring( obj )
     16 	end
     17 
     18 	if t == "string" then
     19 		return "%q" % obj
     20 	end
     21 
     22 	if t == "table" then
     23 		local output = "{ "
     24 
     25 		for k, v in pairs( obj ) do
     26 			output = output .. "%s = %s, " % { formatKey( k ), serializeObject( v ) }
     27 		end
     28 
     29 		return output .. "}"
     30 	end
     31 
     32 	error( "I don't know how to serialize type " .. t )
     33 end
     34 
     35 local function serialize( obj )
     36 	if not obj then
     37 		return "return { }"
     38 	end
     39 
     40 	return "return " .. serializeObject( obj )
     41 end
     42 
     43 local function serializeUnwrapped( obj )
     44 	local output = ""
     45 
     46 	for k, v in pairs( obj ) do
     47 		output = output .. "%s = %s\n" % { k, serializeObject( v ) }
     48 	end
     49 
     50 	return output
     51 end
     52 
     53 return {
     54 	wrapped = serialize,
     55 	unwrapped = serializeUnwrapped,
     56 }