/lib/config.lua
Lua | 60 lines | 50 code | 8 blank | 2 comment | 4 complexity | e11513b11986d81a80a6353abd5517b7 MD5 | raw file
-
- require("std")
- local prettytostring = prettytostring
- local lfs = require("lfs")
- local io = io
- local setmetatable = setmetatable
- local loadstring = loadstring
- local pairs = pairs
-
- module("config")
-
-
- function new(filepath,default_config)
- local _t
-
- local function save_config()
- local f = io.open(filepath,"w")
- f:write(prettytostring(_t))
- f:close()
- --print(prettytostring(_t))
- end
-
- if lfs.attributes(filepath) then
- local f = io.open(filepath,"r")
- local s = f:read("*a")
- local f2 = loadstring("local t = "..s.." return t")
- f:close()
- _t = f2()
-
- local modified = false
- --make sure all config key have value
- for k,v in pairs(default_config) do
- if _t[k]==nil then
- _t[k]=v
- modified = true
- end
- end
- if modified then save_config() end
- else
- _t = default_config
- save_config()
- end
-
- local proxy = {}
- local proxy_mt =
- {
- __index =
- function(t,k)
- return _t[k]
- end
- ,
- __newindex =
- function(t,k,v)
- _t[k]=v
- save_config()
- end
- }
- setmetatable(proxy,proxy_mt)
- return proxy
- end