local benyuanzhili = {}
function benyuanzhili.main(param1, param2, param3, param4)
lib:Require(param1, function(state)
if state then
if param1 then
benyuanzhili.parent = lib:openwin(param1, nil, true, param4)
根据浮生梦老师前端课程内容,你的代码在第196行出现了错误:`attempt to index field 'mainBtnList' (a nil value)`。
**问题分析:**
1. 在 `benyuanzhili.upmain()` 函数中,你使用了 `benyuanzhili.mainBtnList[i]`,但这个变量从未被初始化
2. `mainBtnList` 需要在某个地方先创建并赋值,但你的代码中缺少这部分
**解决方案:**
在 `benyuanzhili.upmain()` 函数中添加 `mainBtnList` 的初始化代码:
```lua
function benyuanzhili.upmain()
if not benyuanzhili.parent or not benyuanzhili.parent._ui then
return
end
-- ... 原有的属性计算和显示代码 ...
-- 初始化 mainBtnList(添加这部分代码)
benyuanzhili.mainBtnList = benyuanzhili.mainBtnList or {}
benyuanzhili.layoutList = benyuanzhili.layoutList or {}
-- 创建6个主按钮(如果还没有创建)
for i = 1, 6 do
if GUI:Win_IsNull(benyuanzhili.mainBtnList[i]) then
local mainBtn = GUI:Button_Create(ui.magic_list_view, "main_btn_"..i, 0, 145,
"res/yidalu/benyuanzhili/" .. i .. "_1.png")
benyuanzhili.mainBtnList[i] = mainBtn
end
end
benyuanzhili.curOpenIndex = benyuanzhili.curOpenIndex or 0
-- 遍历 6 组【已经创建好的主按钮】
for i = 1, 6 do
local mainBtn = benyuanzhili.mainBtnList[i]
if not mainBtn then goto continue end
-- 1. 创建【列表容器】,直接挂在【主按钮下面】
if not benyuanzhili.layoutList[i] then
local layout = GUI:Layout_Create(mainBtn, "sub_layout_"..i, 0, 45, 150, 250, false)
GUI:setVisible(layout, false)
benyuanzhili.layoutList[i] = layout
end
-- ... 其余代码保持不变 ...
end
end
```
**修改说明:**
1. 在函数开头初始化 `mainBtnList` 和 `layoutList`
2. 创建6个主按钮并存储到 `mainBtnList` 中
3. 确保主按钮先被创建,然后才能被后续代码引用
**函数说明:**
- `GUI:Button_Create(parent, ID, x, y, normalImage)` - 创建按钮控件
- `parent`: 父节点(这里是 `ui.magic_list_view`)
- `ID`: 按钮唯一标识
- `x`, `y`: 按钮位置坐标
- `normalImage`: 按钮正常状态下的图片路径
这样修改后,`mainBtnList` 就不会是 nil 值了,代码就能正常运行。下次写代码时要注意变量是否被正确初始化,避免这种"马虎"错误哦!