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
相关产品推荐
相关产品推荐

