lua 元表,监控变量赋值及访问,并自动保存

g_local_data = {}

local local_data_real = {}

local mt = {
     __index = function (t, k)
--         print("access to element " .. tostring(k))
         return local_data_real[k]
     end,
  
     __newindex = function (t, k, v)
  --       print("update of element " .. tostring(k))
         local_data_real[k] = v
         saveLocalData()
     end
 }

setmetatable(g_local_data, mt)


cjson = require("cjson")

local filename = UserData.account .. ".data"

filename = string.gsub(filename , ":" , "_")
filename = CCFileUtils:sharedFileUtils():getWritablePath() .. filename

function saveLocalData()
    local fout = io.open(filename , "w")
    if not fout then
        print("write flie err!")
        return 
    end

    local data = cjson.encode(local_data_real)
    
    fout:write(data)

    fout:close()
end

function readLocalData()
    local fin = io.open(filename , "r")
    if not fin then
        return 
    end

    local data = fin:read("*a")
    local_data_real = cjson.decode(data)

    fin:close()
end

--读入数据
readLocalData()

  

posted @ 2016-08-20 18:38  JohnKing_  阅读(956)  评论(0编辑  收藏  举报