VaiN474

[SALT] Save and Load Tables

Jan 28th, 2015
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.78 KB | None | 0 0
  1. --[[ [SALT] Save and Load Tables - By VaiN ]]--
  2. function table.save(tbl,file)
  3.     -- make sure the table exists
  4.     if not tbl then
  5.         print("Error: Unable to save table, nil value")
  6.         return
  7.     end
  8.    
  9.     -- recursively saves table data to a file, human-readable and indented
  10.     -- supported types: number, string, boolean, tables of the same
  11.     local f,err = io.open(file,"w")
  12.     if err then
  13.         print("Error: Unable to open file for writing: "..file.."\nDetails: "..err)
  14.         return
  15.     end
  16.     local indent = 1
  17.  
  18.     -- local functions to make things easier
  19.     local function exportstring(s)
  20.         s=string.format("%q",s)
  21.         s=s:gsub("\\\n","\\n")
  22.         s=s:gsub("\r","")
  23.         s=s:gsub(string.char(26),"\"..string.char(26)..\"")
  24.         return s
  25.     end
  26.     local function serialize(o)
  27.         if type(o) == "number" then
  28.             f:write(o)
  29.         elseif type(o) == "boolean" then
  30.             if o then f:write("true") else f:write("false") end
  31.         elseif type(o) == "string" then
  32.             f:write(exportstring(o))
  33.         elseif type(o) == "table" then
  34.             f:write("{\n")
  35.             indent = indent + 1
  36.             local tab = ""
  37.             for i=1,indent do tab = tab .. "    " end
  38.             for k,v in pairs(o) do
  39.                 f:write(tab .. "[")
  40.                 serialize(k)
  41.                 f:write("] = ")
  42.                 serialize(v)
  43.                 f:write(",\n")
  44.             end
  45.             indent = indent - 1
  46.             tab = ""
  47.             for i=1,indent do tab = tab .. "    " end
  48.             f:write(tab .. "}")
  49.         else
  50.             print("unable to serialzie data: " .. tostring(o))
  51.             f:write("nil, -- ***ERROR: unsupported data type!***")
  52.         end
  53.     end
  54.  
  55.     -- here's the actual save process
  56.     f:write("return {\n")
  57.     for k,v in pairs(tbl) do
  58.         f:write("   [")
  59.         serialize(k)
  60.         f:write("] = ")
  61.         serialize(v)
  62.         f:write(",\n")
  63.     end
  64.     f:write("}")
  65.     f:close()
  66. end
  67. function table.load(file)
  68.     local data,err = loadfile(file)
  69.     if err then return nil,err else return data() end
  70. end
Advertisement
Add Comment
Please, Sign In to add comment