分装cc.mvc.ModelBase,方便序列化模型对象的属性值,统一getter&setter接口


– Author: footprint
– Date: 2014-09-24 16:26:14

local SGModelBase = class(“SGModelBase”, cc.mvc.ModelBase)

SGModelBase.events = {} --事件映射

function SGModelBase:getProperty(key)
local k = “get”…string.sub(string.upper(string.sub(key, 1, 1)), 1)…string.sub(key, 2)

if self then --是否重写了getter方法
    return self(self)
else
    return self
end

end

function SGModelBase:setProperty(key, value)
local k = “set”…string.sub(string.upper(string.sub(key, 1, 1)), 1)…string.sub(key, 2)

if self then --是否重写了setter方法
    self(self, value)
else
    local event = nil
    if SGModelBase.events and SGModelBase.events then --event
        local from = self:getProperty(key)
        event = {name = SGModelBase.events, from = from, to = value}            
    end

    self = value --set value

    if event then
        self:dispatchEvent(event)
    end
end

end

–深度转换模型对象为键值对table,不支持userdata类型
function SGModelBase:schemas()
local function _schemas(t)
if type(t) ~= “table” then
return t
end

    local ret = {}

    if iskindof(t, "ModelBase") then
        local schema = t.schema

        for k,v in pairs(schema) do
            local key_ = k.."_"
            local value = t

            ret = _schemas(value)
        end
    else
        for k,v in pairs(t) do
            ret = _schemas(v)
        end
    end

    return ret
end

return _schemas(self)

end

–序列化输出lua字符串
function SGModelBase:toLuaString()
local t = self:schemas()
return table.serialize(t)
end

return SGModelBase

–序列化函数,只支持number或string做key,value可以是一个table ,并支持循环引用
–通过loadstring加载,返回的是一个function
–修改from:http://blog.codingnow.com/cloud/LuaSerializeTable
function table.serialize(t)
local mark={}
local assign={}

local function ser_table(tbl,parent)
    mark=parent
    local tmp={}
    for k,v in pairs(tbl) do
        local key= type(k)=="number" and ""..k.."]" or k
        if type(v)=="table" then
            local dotkey= parent..(type(k)=="number" and key or "."..key)
            if mark then
                table.insert(assign,dotkey.."="..mark)
            else
                table.insert(tmp, key.."="..ser_table(v,dotkey))
            end
        else
            if type(v)=="number" then
                table.insert(tmp, key.."="..v)
            else
                table.insert(tmp, key.."=\""..tostring(v).."\"")
            end
        end
    end
    return "{"..table.concat(tmp,",").."}"
end

return "do local ret="..ser_table(t,"ret")..table.concat(assign," ").." return ret end"

end

:2::2::2:顶顶