Advertisement
lavalevel

loadsave functions

Oct 3rd, 2013
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.68 KB | None | 0 0
  1. local _ = {}
  2. local json = require("Json")
  3. local DefaultLocation = system.DocumentsDirectory
  4. local RealDefaultLocation = DefaultLocation
  5. local ValidLocations = {
  6.    [system.DocumentsDirectory] = true,
  7.    [system.CachesDirectory] = true,
  8.    [system.TemporaryDirectory] = true
  9. }
  10.  
  11. function _.saveTable(t, filename, location)
  12.     if location and (not ValidLocations[location]) then
  13.      error("Attempted to save a table to an invalid location", 2)
  14.     elseif not location then
  15.       location = DefaultLocation
  16.     end
  17.    
  18.     local path = system.pathForFile( filename, location)
  19.     local file = io.open(path, "w")
  20.     if file then
  21.         local contents = json.encode(t)
  22.         file:write( contents )
  23.         io.close( file )
  24.         return true
  25.     else
  26.         return false
  27.     end
  28. end
  29.  
  30. function _.loadTable(filename, location)
  31.     if location and (not ValidLocations[location]) then
  32.      error("Attempted to load a table from an invalid location", 2)
  33.     elseif not location then
  34.       location = DefaultLocation
  35.     end
  36.     local path = system.pathForFile( filename, location)
  37.     local contents = ""
  38.     local myTable = {}
  39.     local file = io.open( path, "r" )
  40.     if file then
  41.         -- read all contents of file into a string
  42.         local contents = file:read( "*a" )
  43.         myTable = json.decode(contents);
  44.         io.close( file )
  45.         return myTable
  46.     end
  47.     return nil
  48. end
  49.  
  50. function _.changeDefault(location)
  51.     if location and (not location) then
  52.         error("Attempted to change the default location to an invalid location", 2)
  53.     elseif not location then
  54.         location = RealDefaultLocation
  55.     end
  56.     DefaultLocation = location
  57.     return true
  58. end
  59.  
  60. return _
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement