Advertisement
alestane

Preferences module

Jan 16th, 2012
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.98 KB | None | 0 0
  1. local json = require "json"
  2.  
  3. local function decodeFile(path)
  4.     local file = io.open(path)
  5.     if file then
  6.         local body = file:read('a*')
  7.         file:close()
  8.         return json.decode(body)
  9.     end
  10. end
  11.  
  12. local function encodeFile(path, object)
  13.     local file = io.open(path, 'w')
  14.     if file then
  15.         file:write(json.encode(object))
  16.         file:close()
  17.     end
  18. end
  19.  
  20. local defaults = {
  21.     name = 'Settings';
  22.     Sound = {
  23.         Volume = 1
  24.     },
  25.     Music = {
  26.         Volume = 1
  27.     },
  28.     Guides = {
  29.         Show = true
  30.     }
  31. }
  32.  
  33. local storagePath = system.pathForFile("Scrapyard.preferences", system.DocumentsDirectory)
  34. local valid, preferences = pcall(decodeFile, storagePath)
  35. if not valid then preferences = {} end
  36.  
  37. setmetatable(preferences, {__index = defaults})
  38. Runtime:dispatchEvent(preferences)
  39.  
  40. Runtime:addEventListener('Settings',
  41.     function(event)
  42.         for name, value in pairs(event) do
  43.             if name ~= 'name' then
  44.                 preferences[name] = value
  45.             end
  46.         end
  47.         encodeFile(storagePath, preferences)
  48.     end
  49. )
  50.  
  51. return preferences
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement