Bag = {}
function Bag.Init(isWin32)
-- 网格配置
Bag._ScrollHeight = isWin32 and 214 or 320 -- 容器滚动区域的高度
Bag._PWidth = isWin32 and 338 or 500 -- 容器可见区域 宽
Bag._PHeight = isWin32 and 214 or 320 -- 容器可见区域 高
Bag._IWidth = isWin32 and 42.8 or 62.5 -- item 宽
B
根据浮生梦老师前端课程内容,我发现了你代码中的问题。在 `Bag.GetItemData()` 函数中,你使用了 `makeidx` 变量但未定义它,应该是 `pos` 变量。
**问题所在:**
```lua
-- 错误代码(第45行):
local itemData = SL:GetMetaValue("ITEM_DATA_BY_MAKEINDEX", makeidx, false)
-- 应该改为:
local itemData = SL:GetMetaValue("ITEM_DATA_BY_MAKEINDEX", pos, false)
```
**正确的 `Bag.GetItemData()` 函数修改:**
```lua
function Bag.GetItemData()
Bag._itemList = {}
local maxBag = SL:GetMetaValue("MAX_BAG") or 0
if not maxBag or maxBag == 0 then
SL:Print("背包容量为0")
return
end
for _, itemName in ipairs(Bag._targetItemIds) do
local found = false
local itemIdx = SL:GetMetaValue("ITEM_INDEX_BY_NAME", itemName)
if not itemIdx then
SL:Print("物品名称不存在:" .. itemName)
goto continue
end
local totalCount = SL:GetMetaValue("ITEM_COUNT", itemIdx)
if not totalCount or totalCount <= 0 then
SL:Print("背包中没有物品:" .. itemName)
goto continue
end
-- 遍历背包查找具体位置
for pos = 1, maxBag do
-- 修改这里:使用pos而不是未定义的makeidx
local itemData = SL:GetMetaValue("ITEM_DATA_BY_MAKEINDEX", pos, false)
if itemData and itemData.id == itemIdx and (itemData.count or 0) > 0 then
local displayName = SL:GetMetaValue("ITEM_NAME", itemIdx)
local iconPath = SL:GetMetaValue("ITEM_ICON", itemIdx)
table.insert(Bag._itemList, {
id = itemIdx,
name = itemName,
pos = pos,
count = itemData.count or 0,
icon = iconPath or "",
makeIndex = itemData.makeIndex,
displayName = displayName or itemName
})
SL:Print("在背包位置" .. pos .. "找到物品:" .. itemName ..
",数量:" .. (itemData.count or 0) ..
",索引ID:" .. itemIdx)
found = true
break
end
end
if not found and totalCount > 0 then
SL:Print("警告:统计有" .. totalCount .. "个" .. itemName ..
",但未在背包格子中找到")
end
::continue::
end
SL:Print("获取到指定物品数量:" .. #Bag._itemList)
if #Bag._itemList == 0 then
SL:Print("背包中未找到指定物品")
end
if Bag.UpdateItemDisplay then
Bag.UpdateItemDisplay()
end
end
```
**参数说明:**
- `SL:GetMetaValue("ITEM_DATA_BY_MAKEINDEX", pos, false)`
- 第一个参数:函数标识符
- 第二个参数:背包位置索引(pos)
- 第三个参数:false 表示获取普通物品数据(非英雄)
这样修改后,代码就能正确遍历背包每个位置查找指定物品了。下次写代码时要注意变量名的一致性,避免使用未定义的变量!