Advertisement
Guest User

Untitled

a guest
Dec 25th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. local M = {}
  2.  
  3. local json = require( "json" )
  4. local defaultLocation = system.DocumentsDirectory
  5.  
  6.  
  7. function M.saveTable( t, filename, location )
  8.  
  9. local loc = location
  10. if not location then
  11. loc = defaultLocation
  12. end
  13.  
  14. -- Path for the file to write
  15. local path = system.pathForFile( filename, loc )
  16.  
  17. -- Open the file handle
  18. local file, errorString = io.open( path, "w" )
  19.  
  20. if not file then
  21. -- Error occurred; output the cause
  22. print( "File error: " .. errorString )
  23. return false
  24. else
  25. -- Write encoded JSON data to file
  26. file:write( json.encode( t ) )
  27. -- Close the file handle
  28. io.close( file )
  29. return true
  30. end
  31. end
  32.  
  33. function M.loadTable( filename, location )
  34.  
  35. local loc = location
  36. if not location then
  37. loc = defaultLocation
  38. end
  39.  
  40. -- Path for the file to read
  41. local path = system.pathForFile( filename, loc )
  42.  
  43. -- Open the file handle
  44. local file, errorString = io.open( path, "r" )
  45.  
  46. if not file then
  47. -- Error occurred; output the cause
  48. print( "File error: " .. errorString )
  49. else
  50. -- Read data from file
  51. local contents = file:read( "*a" )
  52. -- Decode JSON data into Lua table
  53. local t = json.decode( contents )
  54. -- Close the file handle
  55. io.close( file )
  56. -- Return table
  57. return t
  58. end
  59. end
  60.  
  61. return M
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement