Advertisement
Tatantyler

Serializer API

Sep 2nd, 2012
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.31 KB | None | 0 0
  1. local function postprocessing(toProcess)
  2.     local parameters = {}
  3.     for index, value in ipairs(toProcess) do
  4.         if tonumber(value) ~= nil then
  5.             table.insert(parameters, tonumber(value))
  6.         elseif textutils.unserialize(value) ~= nil then
  7.             table.insert(parameters, textutils.unserialize(value))
  8.         else
  9.             table.insert(parameters, value)
  10.         end
  11.     end
  12.     return parameters, #parameters
  13. end
  14.  
  15. function deserialize(message)
  16.     local position = 1
  17.     local parameters = {}
  18.     while true do
  19.         local colonPos = string.find(message, ":", position)
  20.         if colonPos == nil then
  21.             table.insert(parameters, string.sub(message,position))
  22.             break
  23.         else
  24.             table.insert(parameters, string.sub(message,position, colonPos-1))
  25.         end
  26.         position = colonPos+1
  27.     end
  28.     return postprocessing(parameters)
  29. end
  30.  
  31. function serialize(...)
  32.     local encodedString = ""
  33.     for index, value_original in ipairs(arg) do
  34.         local value = value_original
  35.         if type(value) == "number" then
  36.             value = tostring(value_original)
  37.         elseif type(value) == "table" then
  38.             value = textutils.serialize(value_original)
  39.         end
  40.         if type(value) ~= "string" then
  41.             error("serialize() expects either strings, numbers, or tables")
  42.         end
  43.         if index == 1 then
  44.             encodedString = value
  45.         else
  46.             encodedString = encodedString..":"..value
  47.         end
  48.     end
  49.     return encodedString
  50. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement