我是lua后端老师!
小仙,你这段代码要实现“装备首爆”功能,但在`addbagbefore`触发函数里逻辑有些混乱,还用了些不存在的函数。我来帮你梳理一下,指出问题并给出修正建议。
```lua
function B.addbagbefore(actor, item, itemidx, itemMakeIndex)
-- 问题1: eqExpose变量初始化为nil,后面又判断if eqExpose then,这里永远为false
-- 应该直接获取系统变量
local eqExposeJson = getsysvar("装备首爆")
-- 问题2: 这里应该判断eqExposeJson是否为空,如果为空说明是第一次,需要初始化
if eqExposeJson == nil or eqExposeJson == "" then
-- 初始化系统变量,存储首爆记录
inisysvar("string", "装备首爆", "{}") -- 初始化为空JSON
eqExposeJson = "{}"
end
-- 将JSON字符串转换为table
local firstExplosion = json2tbl(eqExposeJson)
if firstExplosion == nil then
firstExplosion = {}
end
-- 检查是否有"王者特权"称号
local hasTitle = checktitle(actor, "王者特权")
-- 遍历装备表查找匹配的装备
local found = false
local rewardCount = 0
local itemName = ""
-- 问题3: 你的双层循环逻辑有问题,应该是遍历所有子表
for page = 1, 28 do
if B.eqExposeTbl[page] then
for _, equip in ipairs(B.eqExposeTbl[page]) do
if equip.idx == itemidx then
found = true
rewardCount = equip.rewardCount
itemName = equip.name
-- 检查是否已经首爆过
local key = tostring(itemidx)
if firstExplosion[key] == nil then
-- 首次爆出,记录信息
firstExplosion[key] = {
isExpose = 1,
time = os.date("%Y年%m月%d日%H时%M分%S秒"),
map = getmapname(actor) -- 获取当前地图名
}
-- 根据称号给予不同金币
if hasTitle then
-- 问题4: takebindmoney函数不存在,应该是giveitem给金币道具
-- 假设金币的itemidx是1
giveitem(actor, 1, rewardCount)
sendmsg(actor, "恭喜你作为王者特权玩家,首次爆出"..itemName..",获得"..rewardCount.."金币!", 1)
else
giveitem(actor, 1, rewardCount) -- 给绑定金币
sendmsg(actor, "恭喜你首次爆出"..itemName..",获得"..rewardCount.."绑定金币!", 1)
end
-- 全服公告
sendmsg(0, "玩家【"..actor.."】在"..firstExplosion[key].map.."首次爆出"..itemName.."!", 1)
-- 保存更新后的首爆记录
local newJson = tbl2json(firstExplosion)
setsysvarex("装备首爆", newJson, 1)
end
break
end
end
end
if found then break end
end
end
```
主要问题总结:
1. **变量初始化逻辑错误**:`eqExpose`初始化为nil,后面的判断永远为false
2. **循环逻辑混乱**:双层遍历的方式不对,应该直接遍历所有装备
3. **使用了不存在的函数**:`takebindmoney`函数不存在,应该用`giveitem`
4. **系统变量操作不当**:应该先判断是否存在,再转换JSON
5. **数据结构设计问题**:`firstExplosion`作为局部变量,应该从系统变量读取
建议改进:
1. 使用`giveitem`函数给予金币奖励
2. 简化装备查找逻辑
3. 使用装备idx作为key存储首爆记录
4. 添加适当的提示信息
记住,`addbagbefore`触发是物品进包前的触发,不能阻止进包操作,但可以在这里记录信息和给予额外奖励。如果还有不懂的,可以问我或者浮生梦尊师!