PageRenderTime 19ms CodeModel.GetById 13ms app.highlight 3ms 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
 2require("std")
 3local prettytostring = prettytostring
 4local lfs = require("lfs")
 5local io = io
 6local setmetatable = setmetatable
 7local loadstring = loadstring
 8local pairs = pairs
 9
10module("config")
11
12
13function new(filepath,default_config)
14    local _t
15    
16    local function save_config()
17        local f = io.open(filepath,"w")
18        f:write(prettytostring(_t))
19        f:close()
20        --print(prettytostring(_t))
21    end
22    
23    if lfs.attributes(filepath) then
24        local f = io.open(filepath,"r")
25        local s = f:read("*a")
26        local f2 = loadstring("local t = "..s.." return t")
27        f:close()
28        _t = f2()
29        
30        local modified = false
31        --make sure all config key have value
32        for k,v in pairs(default_config) do
33            if _t[k]==nil then
34                _t[k]=v
35                modified = true
36            end
37        end
38        if modified then save_config() end
39    else
40        _t = default_config
41        save_config()
42    end
43    
44    local proxy = {}
45    local proxy_mt =
46    {
47        __index =
48            function(t,k)
49                return _t[k]
50            end
51        ,
52        __newindex =
53            function(t,k,v)
54                _t[k]=v
55                save_config()
56            end
57    }
58    setmetatable(proxy,proxy_mt)
59    return proxy
60end