PageRenderTime 39ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/config.lua

https://code.google.com/p/phonecom/
Lua | 60 lines | 50 code | 8 blank | 2 comment | 4 complexity | e11513b11986d81a80a6353abd5517b7 MD5 | raw file
  1. require("std")
  2. local prettytostring = prettytostring
  3. local lfs = require("lfs")
  4. local io = io
  5. local setmetatable = setmetatable
  6. local loadstring = loadstring
  7. local pairs = pairs
  8. module("config")
  9. function new(filepath,default_config)
  10. local _t
  11. local function save_config()
  12. local f = io.open(filepath,"w")
  13. f:write(prettytostring(_t))
  14. f:close()
  15. --print(prettytostring(_t))
  16. end
  17. if lfs.attributes(filepath) then
  18. local f = io.open(filepath,"r")
  19. local s = f:read("*a")
  20. local f2 = loadstring("local t = "..s.." return t")
  21. f:close()
  22. _t = f2()
  23. local modified = false
  24. --make sure all config key have value
  25. for k,v in pairs(default_config) do
  26. if _t[k]==nil then
  27. _t[k]=v
  28. modified = true
  29. end
  30. end
  31. if modified then save_config() end
  32. else
  33. _t = default_config
  34. save_config()
  35. end
  36. local proxy = {}
  37. local proxy_mt =
  38. {
  39. __index =
  40. function(t,k)
  41. return _t[k]
  42. end
  43. ,
  44. __newindex =
  45. function(t,k,v)
  46. _t[k]=v
  47. save_config()
  48. end
  49. }
  50. setmetatable(proxy,proxy_mt)
  51. return proxy
  52. end