根据浮生梦老师前端课程内容,你遇到的 `cfg[i].where` 错误可能不是数据本身的问题,而是访问时机或对象状态的问题。
**问题分析:**
1. `cfg` 数据虽然正确,但可能在访问时 `cfg[i]` 对象还未完全初始化
2. 组件创建时参数传递有问题
3. 数据格式虽然正确,但访问方式不对
**解决方案:**
```lua
-- 1. 先确保 cfg 是表格类型
if type(cfg) ~= "table" then
SL:Print("cfg 不是表格类型!")
return
end
-- 2. 检查索引有效性
local index = i or 1
if index < 1 or index > #cfg then
SL:Print("索引 " .. index .. " 超出范围,cfg长度:" .. #cfg)
return
end
-- 3. 安全获取 equipID
local equipID = nil
if cfg[index] and type(cfg[index]) == "table" then
equipID = cfg[index].where
end
-- 4. 验证 equipID
if not equipID or type(equipID) ~= "number" then
SL:Print("equipID 无效或不是数字类型")
return
end
-- 5. 创建 EquipShow(确保 img 是有效的父节点)
local equip = GUI:EquipShow_Create(img, "where"..index, 0, 0, equipID, true, data)
if not equip then
SL:Print("EquipShow 创建失败!")
return
end
```
**调试建议:**
1. 在访问前打印完整数据:`SL:dump(cfg[index], "cfg["..index.."]内容")`
2. 检查 `img` 参数是否有效:`if GUI:Win_IsNull(img) then SL:Print("img 无效") end`
3. 确保 `data` 参数格式正确
**常见原因:**
1. 数据异步加载,访问时还未准备好
2. 索引 `i` 的计算逻辑有误
3. `cfg` 虽然存在,但某些元素是 `nil`
下次遇到这种问题,可以先检查数据加载的时机,确保在数据完全准备好后再访问。不懂的可以问浮生梦老师!