Advertisement
Bolodefchoco_LUAXML

[Function] Serialization

Mar 24th, 2016
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.67 KB | None | 0 0
  1. --Creator: Bolodefchoco
  2. --Made in: 24/03/2016
  3. --Last update: 01/04/2017
  4. --[[ Notes:
  5.     Does:
  6.         Caso x seja uma tabela
  7.             Faz com que a tabela vire uma string
  8.         Caso x seja uma string
  9.             Faz com que a string vire uma tabela
  10.     Args:
  11.         x --> Informação a ser transformada
  12. ]]--
  13.  
  14. serialization = function(x)
  15.     if type(x) == "table" then
  16.         local str = {}
  17.  
  18.         for index,value in next,x do
  19.             local v = type(value)
  20.  
  21.             local prefix = (v == "string" and "@" or v == "boolean" and "!" or v == "number" and "#" or v == "table" and "%" or "")
  22.             if prefix then
  23.                 local data
  24.                 if prefix == "@" then
  25.                     data = table.concat({string.byte(value,1,#value)},".")
  26.                 elseif prefix == "!" then
  27.                     data = (value and 1 or 0)
  28.                 elseif prefix == "#" then
  29.                     data = tostring(value)
  30.                 elseif prefix == "%" then
  31.                     data = string.format("{%s}",serialization(value):gsub(";","?"))
  32.                 end
  33.  
  34.                 str[#str + 1] = string.format(":%s%s%s;",index,prefix,data)
  35.             end
  36.         end
  37.  
  38.         return table.concat(str)
  39.     elseif type(x) == "string" then
  40.         local list = {}
  41.        
  42.         for str in x:gmatch("(.-);") do
  43.             local index,vtype,value = str:match(":(.-)(%p)(.+)")
  44.             if index and vtype and value then
  45.                 index = tonumber(index) or index
  46.  
  47.                 if vtype == "@" then
  48.                     local sub = {}
  49.                     for i in value:gmatch("[^%.]+") do
  50.                         sub[#sub+1] = i
  51.                     end
  52.                     list[index] = string.char(table.unpack(sub))
  53.                 elseif vtype == "!" then
  54.                     list[index] = (value == "1")
  55.                 elseif vtype == "#" then
  56.                     list[index] = tonumber(value)
  57.                 elseif vtype == "%" then
  58.                     list[index] = serialization(value:gsub("{",""):gsub("}",""):gsub("%?",";"))
  59.                 end
  60.             end
  61.         end
  62.  
  63.         return list
  64.     end
  65. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement