lua配置表优化以及元表

table1 = 
{
	[100] = {
		Hung = 0,
		IDType = 7,
		InitMapID = 10000,
		Name = "荣誉阶梯",
		Timeout = 0
	},
	[101] = {
		Hung = 0,
		IDType = 0,
		InitMapID = 10100,
		MinLv = 50,
		Name = "盘山道",
		NumEveryDay = 1,
		PworldID = 101,
		Timeout = 1200,
		Type = 2
	}
}


local __default_values = {
	Cheats = "",
	ClientCtrlFlag = 0,
	Des = "",
	DungeonEffect = 0,
	EnterUseVig = 0,
	FailBtnFlag = 7,
	GeneralWaveID = 0,
	Hung = 2,
	IDType = 26,
	InitMapID = 0,
	MaxLv = 0,
	MinLv = 0,
	Name = "守护者副本",
	NumEveryDay = 0,
	OpeningEffect_Delay = 0,
	OpeningEffect_Id = 0,
	OpeningEffect_Time = 0,
	PopAlive = 0,
	PworldID = 100,
	RelativeID = 0,
	ResourceID = "",
	StartPositon = 0,
	Timeout = 300,
	Type = 0,
	Typemain = 0,
	exit = 0,
	exit2 = 0,
	q_isscript = 0
}

local mt = {
    __index = function(tbl, key)
        local val = rawget(tbl, key)
        if val then 
            return val
        else 
            return __default_values[key]
        end
    end,
    
    __newindex = function(tbl, key, value)
        rawset(tbl, key, value)
    end,

    __pairs = function (tbl)
		local func = function (tbl, key)
			local nk, nv = next(__default_values, key)
				if nk then 
					nv = tbl[nk]
				end
				return nk, nv
			end
        return func, tbl, nil
    end
}

-- 设置元表
for _,item in pairs(table1) do
    setmetatable(item, mt)
end

GetList = function()
	--不用元表可以使用填充的方式
	--[[for _, tbl in pairs(table1) do
		for key, value in pairs(__default_values) do
			local val = rawget(tbl, key)
			if val==nil then
				rawset(tbl, key, value)
			end
		end
	end--]]
	return table1; 
end;

Get = function(id) 
	if table1[id] == nil then
		PrintConfig(string.format("X_itemdef表id %s 的数据为空!",id))
	end
	return table1[id]; 
end;


for k, tbl in pairs(GetList()) do
	for m, n in pairs(tbl) do
		print(k, m, n)
	end
end






你可能感兴趣的:(ios)