Advertisement
lvs

Serialize table to Lua file

lvs
Sep 23rd, 2013
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 6.83 KB | None | 0 0
  1. local n, v = "serpent", 0.23 -- (C) 2012-13 Paul Kulchenko; MIT License
  2. local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
  3. local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
  4. local badtype = {thread = true, userdata = true, cdata = true}
  5. local keyword, globals, G = {}, {}, (_G or _ENV)
  6. for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
  7.   'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
  8.   'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
  9. for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
  10. for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
  11.   for k,v in pairs(G[g]) do globals[v] = g..'.'..k end end
  12.  
  13. local function s(t, opts)
  14.   local name, indent, fatal = opts.name, opts.indent, opts.fatal
  15.   local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
  16.   local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
  17.   local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
  18.   local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
  19.   local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
  20.     -- tostring(val) is needed because __tostring may return a non-string value
  21.     function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return syms[s] end)) end
  22.   local function safestr(s) return type(s) == "number" and (huge and snum[tostring(s)] or s)
  23.     or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
  24.     or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
  25.   local function comment(s,l) return '' end
  26.   local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
  27.     and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
  28.   local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
  29.     local n = name == nil and '' or name
  30.     local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
  31.     local safe = plain and n or '['..safestr(n)..']'
  32.     return (path or '')..(plain and path and '.' or '')..safe, safe end
  33.   local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n)  -- k=keys, o=originaltable, n=padding
  34.     local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
  35.     local function padnum(d) return ("%0"..maxn.."d"):format(d) end
  36.     table.sort(k, function(a,b)
  37.       -- sort numeric keys first: k[key] is non-nil for numeric keys
  38.       return (k[a] and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
  39.            < (k[b] and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
  40.   local function val2str(t, name, indent, insref, path, plainindex, level)
  41.     local ttype, level, mt = type(t), (level or 0), getmetatable(t)
  42.     local spath, sname = safename(path, name)
  43.     local tag = plainindex and
  44.       ((type(name) == "number") and '' or name..space..'='..space) or
  45.       (name ~= nil and sname..space..'='..space or '')
  46.     if seen[t] then -- already seen this element
  47.       table.insert(sref, spath..space..'='..space..seen[t])
  48.       return tag..'nil'..comment('ref', level) end
  49.     if mt and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
  50.       seen[t] = insref or spath
  51.       if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
  52.       ttype = type(t) end -- new value falls through to be serialized
  53.     if ttype == "table" then
  54.       if level >= maxl then return tag..'{}'..comment('max', level) end
  55.       seen[t] = insref or spath
  56.       if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
  57.       local maxn, o, out = #t, {}, {}
  58.       for key = 1, maxn do table.insert(o, key) end
  59.       for key in pairs(t) do if not o[key] then table.insert(o, key) end end
  60.       if opts.sortkeys then alphanumsort(o, t, opts.sortkeys) end
  61.       for n, key in ipairs(o) do
  62.         local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
  63.         if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
  64.         or opts.keyallow and not opts.keyallow[key]
  65.         or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
  66.         or sparse and value == nil then -- skipping nils; do nothing
  67.         elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
  68.           if not seen[key] and not globals[key] then
  69.             table.insert(sref, 'placeholder')
  70.             local sname = safename(iname, gensym(key)) -- iname is table for local variables
  71.             sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
  72.           table.insert(sref, 'placeholder')
  73.           local path = seen[t]..'['..(seen[key] or globals[key] or gensym(key))..']'
  74.           sref[#sref] = path..space..'='..space..(seen[value] or val2str(value,nil,indent,path))
  75.         else
  76.           table.insert(out,val2str(value,key,indent,insref,seen[t],plainindex,level+1))
  77.         end
  78.       end
  79.       local prefix = string.rep(indent or '', level)
  80.       local head = indent and '{\n'..prefix..indent or '{'
  81.       local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
  82.       local tail = indent and "\n"..prefix..'}' or '}'
  83.       return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
  84.     elseif badtype[ttype] then
  85.       seen[t] = insref or spath
  86.       return tag..globerr(t, level)
  87.     elseif ttype == 'function' then
  88.       seen[t] = insref or spath
  89.       local ok, res = pcall(string.dump, t)
  90.       local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
  91.         "loadstring("..safestr(res)..",'@serialized')")..comment(t, level))
  92.       return tag..(func or globerr(t, level))
  93.     else return tag..safestr(t) end -- handle all other types
  94.   end
  95.   local sepr = indent and "\n" or ";"..space
  96.   local body = val2str(t, name, indent) -- this call also populates sref
  97.   local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
  98.   local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
  99.   return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
  100. end
  101.  
  102. local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
  103. return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
  104.   dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
  105.   line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
  106.   block = function(a, opts) return s(a, merge({indent = '  ', sortkeys = true, comment = true}, opts)) end }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement