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._IW
根据浮生梦老师前端课程内容,我来帮你优化背包物品获取功能。使用 `SL:GetMetaValue("BAG_DATA")` 可以更高效地获取背包数据。
```lua
function Bag.GetItemData()
Bag._itemList = {}
-- 使用BAG_DATA获取背包所有物品
local bagData = SL:GetMetaValue("BAG_DATA")
if not bagData or type(bagData) ~= "table" then
SL:Print("背包数据为空或格式错误")
return
end
for _, itemId in ipairs(Bag._targetItemIds) do
for pos, itemData in pairs(bagData) do
if itemData and itemData.id == itemId and (itemData.count or 0) > 0 then
local itemName = SL:GetMetaValue("ITEM_NAME", itemId)
table.insert(Bag._itemList, {
id = itemId,
pos = pos,
name = itemName or "未知物品",
count = itemData.count or 0,
icon = SL:GetMetaValue("ITEM_ICON", itemId),
makeIndex = itemData.makeIndex
})
SL:Print("在背包位置" .. pos .. "找到物品:" .. itemName .. ",数量:" .. (itemData.count or 0))
break
end
end
end
SL:Print("获取到指定物品数量:" .. #Bag._itemList)
if #Bag._itemList == 0 then
SL:Print("背包中未找到指定物品,请确认背包中是否有以下物品:")
for _, itemId in ipairs(Bag._targetItemIds) do
local itemName = SL:GetMetaValue("ITEM_NAME", itemId)
SL:Print("物品ID " .. itemId .. " - " .. (itemName or "未知"))
end
end
if Bag.UpdateItemDisplay then
Bag.UpdateItemDisplay()
end
end
```
**优化说明:**
1. **直接获取背包数据**:`SL:GetMetaValue("BAG_DATA")` 返回的是完整的背包数据表,不需要遍历每个格子位置
2. **提高效率**:避免了多次调用 `SL:GetMetaValue("ITEM_DATA_BY_MAKEINDEX", pos)`,减少函数调用开销
3. **数据格式更清晰**:`BAG_DATA` 返回的是以位置为key的table,结构更直观
**使用建议:**
- 在 `Bag.main` 函数中注册背包数据更新事件:
```lua
SL:RegisterLUAEvent("BAG_DATA_UPDATE", "Bag", function()
Bag.GetItemData()
end)
```
这样当背包物品发生变化时,界面会自动刷新显示最新的物品信息。