Advertisement
lavalevel

optionsData

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