LazyShpee

Simple table save/load

Jul 26th, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.41 KB | None | 0 0
  1. local function istr(ind)
  2.   if type(ind) == 'string' then
  3.     if ind:match('^[a-zA-Z_][a-zA-Z0-9_]*$') then
  4.       return ind
  5.     end
  6.     return '["'..ind:gsub('"', '\\"')..'"]'
  7.   end
  8.   return '['..ind..']'
  9. end
  10.  
  11. local function tdisplay(t, o, i)
  12.   i = i or 0
  13.   o = o or {}
  14.   local indent = o.indent or 2
  15.   local r = ''
  16.  
  17.   r = '{\n'
  18.   for _i, _v in pairs(t) do
  19.     local ty = type(_v)
  20.     r = r .. (' '):rep((i + 1) * indent) .. istr(_i) .. ' = '
  21.     if ty == 'table' then
  22.       r = r .. tdisplay(_v, o, i + 1)
  23.     elseif ty == 'number' or ty == 'boolean' or ty == 'nil' then
  24.       r = r .. tostring(_v)
  25.     elseif ty == 'string' then
  26.       r = r .. '"' .. _v:gsub('"', '\\"') .. '"'
  27.     end
  28.     r = r .. ',\n'
  29.   end
  30.   r = r..(' '):rep(i * indent)..'}'
  31.   return r
  32. end
  33.  
  34. local function tsave(t, f)
  35.   local ts = tdisplay(t)
  36.   local fd = io.open(f, 'w')
  37.   if not fd then return nil, 'Error opening "'..f..'"' end
  38.   fd:write(ts..'\n')
  39.   fd:close()
  40.   return true
  41. end
  42.  
  43. local function tload(f)
  44.   local fd = io.open(f, 'r')
  45.   if not fd then return nil, 'Error opening "'..f..'"' end
  46.   local ts = fd:read('*all') or '{}'
  47.   fd:close()
  48.  
  49.   local func, syntax = load('return '..ts, 'table.load', 't', {})
  50.   if syntax then return nil, syntax end
  51.  
  52.   local status, t = pcall(func)
  53.   if not status then return nil, t end
  54.   return t
  55. end
  56.  
  57. return {
  58.   td = tdisplay,
  59.   save = tsave,
  60.   load = tload
  61. }
Advertisement
Add Comment
Please, Sign In to add comment