Advertisement
rockbandcheeseman

table.save and table.load

Jan 3rd, 2013
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.35 KB | None | 0 0
  1. function table.save(t, filename)
  2.  
  3.     local dir = getprofilepath()
  4.     local file = io.open(dir .. "\\data\\" .. filename, "w")
  5.     local spaces = 0
  6.  
  7.     local function tab()
  8.  
  9.         local str = ""
  10.         for i = 1,spaces do
  11.             str = str .. " "
  12.         end
  13.  
  14.         return str
  15.     end
  16.  
  17.     local function format(t)
  18.  
  19.         spaces = spaces + 4
  20.         local str = "{ "
  21.  
  22.         for k,v in pairs(t) do
  23.             -- Key datatypes
  24.             if type(k) == "string" then
  25.                 k = string.format("%q", k)
  26.             end
  27.  
  28.             -- Value datatypes
  29.             if type(v) == "string" then
  30.                 v = string.format("%q", v)
  31.             elseif v == math.inf then
  32.                 v = "1 / 0"
  33.             end
  34.  
  35.             if type(v) == "table" then
  36.                 if table.len(v) > 0 then
  37.                     str = str .. "\n" .. tab() .. "[" .. k .. "] = " .. format(v) .. ","
  38.                 else
  39.                     str = str .. "\n" .. tab() .. "[" .. k .. "] = {},"
  40.                 end
  41.             else
  42.                 str = str .. "\n" .. tab() .. "[" .. k .. "] = " .. tostring(v) .. ","
  43.             end
  44.         end
  45.  
  46.         spaces = spaces - 4
  47.  
  48.         return string.sub(str, 1, string.len(str) - 1) .. "\n" .. tab() .. "}"
  49.     end
  50.  
  51.     file:write("return " .. format(t))
  52.     file:close()
  53. end
  54.  
  55. function table.load(filename)
  56.  
  57.     local dir = getprofilepath()
  58.     local file = loadfile(dir .. "\\data\\" .. filename)
  59.     if file then
  60.         return file()
  61.     end
  62.    
  63.     return {}
  64. end
  65.  
  66. function table.len(t)
  67.  
  68.     local count = 0
  69.     for k,v in pairs(t) do
  70.         count = count + 1
  71.     end
  72.    
  73.     return count
  74. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement