Guest User

ezf.lua

a guest
Dec 15th, 2017
33
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. GAME.EZF = {}   --easy file loader/saver
  2. local ezf = GAME.EZF
  3.  
  4. if not love.filesystem.exists( "data" ) then
  5.     local a,b = love.filesystem.createDirectory( "data" )
  6. end
  7. --[[if not love.filesystem.exists( "save" ) then
  8.     local a,b = love.filesystem.createDirectory( "save" )
  9. end]]
  10.  
  11. local ezf_data = {}
  12. local changed = {}
  13.  
  14. local whitelist = {
  15.     ["number"] = true,
  16.     ["string"] = true,
  17.     ["boolean"] = true,
  18. }
  19. --tbl:base tbl2:merge-into
  20. local function restricted_merge(tbl,tbl2)
  21.     for k,v in pairs(tbl) do
  22.         local tk,tv = type(k), type(v)
  23.        
  24.         if whitelist[tk] then
  25.             if whitelist[tv] then
  26.                 tbl2[k] = v
  27.             elseif tv == "table" then
  28.                 if tbl2[k] and type(tbl2[k]) == "table" then
  29.                     restricted_merge(tbl,tbl2[k])
  30.                 else
  31.                     local tbl2_2 = {}
  32.                     tbl2[k] = tbl2_2                   
  33.                     restricted_merge(tbl,tbl2_2)
  34.                 end
  35.             end
  36.         end
  37.     end
  38. end
  39.  
  40. function ezf:CreateNewData(nm,tbl)
  41.     local newdata = tbl and restricted_merge(tbl,{}) or {}
  42.     ezf_data[nm] = newdata
  43.     changed[nm] = false
  44.     return newdata
  45. end
  46.  
  47. function ezf:ChangeData(nm,tbl)
  48.     if not ezf_data[nm] then return end
  49.     restricted_merge(tbl,ezf_data[nm])
  50. end
  51.  
  52. function ezf:SaveData(nm)
  53.     if not ezf_data[nm] then return end
  54.     print("Saving: data/"..nm..".txt")
  55.     love.filesystem.write( "data/"..nm..".txt", serp.dump(ezf_data[nm]) )
  56. end
  57.  
  58. function ezf:LoadDataInto(nm,itbl,func)
  59.     print("Loading: data/"..nm..".txt")
  60.    
  61.     if love.filesystem.exists( "data/"..nm..".txt" ) then
  62.         local conts = love.filesystem.read( "data/"..nm..".txt" )
  63.         local ok, ltbl = serp.load(conts)
  64.         restricted_merge(ltbl, itbl)
  65.     end
  66.    
  67.     ezf_data[nm] = itbl
  68.     changed[nm] = false
  69.    
  70.     if func then    --callback function on table change
  71.         setmetatable(itbl,{__newindex = function(self,k,v) rawset(itbl,k,v) func(itbl,k,v) end})
  72.     end
  73.    
  74. end
RAW Paste Data