You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua游戏Inventory保存时条目重复问题排查求助

库存保存条目重复问题排查与修复

问题根源

你的代码里存在嵌套的pairs(items)循环:外层遍历每个物品槽位,内层又完整遍历一遍所有物品。这就导致每有一个物品,就会把全部物品重复添加一次。比如有2个物品时,外层循环执行2次,每次内层都遍历2个物品,最终生成4条数据(每个物品重复2次)。

修复后的代码

function SaveInventory(source, offline)
    local source = source
    local xPlayer = ESX.GetPlayerFromId(source)
    -- local PlayerName = xPlayer.getName()  -- 该变量未使用,可按需保留或删除

    local items = AllItemData[source]  -- 加上local,避免全局变量污染
    local ItemsJson = {}

    if items and table.type(items) ~= 'empty' then
        -- 仅保留一层循环,直接遍历每个槽位的物品
        for slot, item in pairs(items) do
            -- 此处if items[slot]判断冗余,pairs只会遍历表中存在的键值对
            ItemsJson[#ItemsJson + 1] = {
                name = item.name,
                amount = item.amount,
                info = item.info,
                type = item.type,
                slot = item.slot,
            }
        end

        MySQL.prepare('UPDATE users SET inventory = ? WHERE identifier = ?', { json.encode(ItemsJson), xPlayer.identifier })
    end
end

额外优化建议

  • 给items变量添加local修饰,避免意外修改全局变量
  • 移除冗余的if items[slot]判断,简化代码逻辑
  • 删除未使用的PlayerName变量,减少代码冗余

内容的提问来源于stack exchange,提问作者Avanae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 11:12:36