我正在创建一个跟踪数据库,收集信息以报告小时,每日,每周,每月,每年,每个级别,每个级别和每层。因此,我有一个名为tracker
的表,它由一个表的子集组成,反映了不同的报告(即table["ThisHour"]
等)。我想知道是否有办法巩固所有这些只是添加相同信息的线路。这是我正在使用的功能,以及两个子表(而不是我上面列出的8个):
function exp_update(xp, gold, str, con, dex, wis, int, luck, bpracs, btrains, pracs, trains, qp)
local xtable = tracker[playername]["Exp"]
addto(xtable["ThisHour"],"Exp",xp)
addto(xtable["ThisHour"],"Gold",gold)
addto(xtable["ThisHour"],"BonusStr",str)
addto(xtable["ThisHour"],"BonusCon",con)
addto(xtable["ThisHour"],"BonusDex",dex)
addto(xtable["ThisHour"],"BonusWis",wis)
addto(xtable["ThisHour"],"BonusInt",int)
addto(xtable["ThisHour"],"BonusLuck",luck)
addto(xtable["ThisHour"],"BonusPracs",bpracs)
addto(xtable["ThisHour"],"BonusTrains",btrains)
addto(xtable["ThisHour"],"Pracs",pracs)
addto(xtable["ThisHour"],"Trains",trains)
addto(xtable["ThisHour"],"Qp",qp)
addto(xtable["ThisHour"],"Quests")
addto(xtable["ThisLevel"],"Exp",xp)
addto(xtable["ThisLevel"],"Gold",gold)
addto(xtable["ThisLevel"],"BonusStr",str)
addto(xtable["ThisLevel"],"BonusCon",con)
addto(xtable["ThisLevel"],"BonusDex",dex)
addto(xtable["ThisLevel"],"BonusWis",wis)
addto(xtable["ThisLevel"],"BonusInt",int)
addto(xtable["ThisLevel"],"BonusLuck",luck)
addto(xtable["ThisLevel"],"BonusPracs",bpracs)
addto(xtable["ThisLevel"],"BonusTrains",btrains)
addto(xtable["ThisLevel"],"Pracs",pracs)
addto(xtable["ThisLevel"],"Trains",trains)
addto(xtable["ThisLevel"],"Qp",qp)
addto(xtable["ThisLevel"],"Quests")
end
正如您所看到的,仅仅两个子表已经有很多行。这是每个子表的14行代码,或者,如果我把它们全部放进去,那么我希望尽可能少地整合112行代码。
addto函数是定义的,如果你需要它:
function addto(t,k,v)
t[k] = t[k] + (v or 1)
end
答案 0 :(得分:3)
我要说这样做:
local function exp_update_actual(vars)
local blocks = {"ThisHour", "ThisLevel"} --Add others as needed.
local xtable = tracker[playername]["Exp"]
for i, block in ipairs(blocks) do
for key, value in pairs(vars) do
addto(xtable[block], key, value)
end
end
end
function exp_update(xp, gold, str, con, dex, wis, int, luck, bpracs, btrains, pracs, trains, qp)
local vars =
{
Exp = xp or false, --nil keys won't exist. false ones will.
Gold = gold or false,
BonusStr = str or false,
BonusCon = con or false,
BonusDex = dex or false,
BonusWis = wis or false,
BonusInt = int or false,
BonusLuck = luck or false,
BonusPracs = bpracs or false,
BonusTrains = btrains or false,
Pracs = pracs or false,
Trains = trains or false,
Qp = qp or false,
Quests = false,
}
exp_update_actual(vars);
end