eniallator

Table Serialiser

Sep 15th, 2016
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.01 KB | None | 0 0
  1. local function serialise(tbl, offset)
  2.   local sTab = {}
  3.   local lastTab = true
  4.   local spaces = ""
  5.  
  6.   if not offset then offset = 0 end
  7.   for i=1, offset do spaces = spaces .. " " end
  8.  
  9.   local i = 1
  10.  
  11.   for key,value in pairs(tbl) do
  12.     local prefix = ""
  13.  
  14.     if key ~= i then
  15.       prefix = "[" .. key .. "] = "
  16.     end
  17.  
  18.     if type(value) == "table" then
  19.       table.insert(sTab, prefix .. serialise(tbl[key], offset + 2))
  20.       lastTab = false
  21.  
  22.     elseif type(value) == "string" then
  23.       table.insert(sTab, prefix .. '"' .. tbl[key] .. '"')
  24.  
  25.     else
  26.       table.insert(sTab, prefix .. tostring(tbl[key]))
  27.     end
  28.  
  29.     i = i +1
  30.   end
  31.  
  32.   local tblStr = "{"
  33.  
  34.   if not lastTab then tblStr = tblStr .. "\n" end
  35.  
  36.   for i=1, #sTab do
  37.     if i ~= 1 then
  38.       tblStr = tblStr .. ","
  39.  
  40.       if not lastTab then tblStr = tblStr .. "\n" end
  41.     end
  42.  
  43.     if not lastTab then tblStr = tblStr .. spaces .. "  " end
  44.  
  45.     tblStr = tblStr .. sTab[i]
  46.   end
  47.  
  48.   if not lastTab then tblStr = tblStr .. "\n" .. spaces end
  49.  
  50.   return tblStr .."}"
  51. end
Advertisement
Add Comment
Please, Sign In to add comment