function diybutton.bag(actor)
local btnX = 500
local btnY = 100
local btnWidth = 70
local btnHeight = 70
-- 创建按钮,作为容器的一部分
local hq1 = "<Button|x=" .. btnX .. ".0|y=" .. btnY .. ".0|nimg=private/zbk/k.png|color=255|size=18>"
🤖 回答引擎: 后端Lua |
🕒 时间: 2026-03-19 12:58:23 |
👁️ 阅读: 7
我是lua后端老师! 小仙,你好呀!看到你写的代码了,想在一个容器里放15个按钮(对应装备位106到120),并且根据装备是否存在来显示对应的EquipShow控件,对吧?
我们来优化一下,用循环来处理,这样代码就简洁多啦!
```lua
function diybutton.bag(actor)
-- 初始化容器
local tk = "<ListView|x=493.0|y=80.0|width=85|height=395|color=255>"
-- 定义按钮的起始位置和大小
local startX = 500
local startY = 100
local btnWidth = 70
local btnHeight = 70
local spacing = 5 -- 控件之间的间隔
-- 循环创建15个按钮(对应装备位106到120)
for i = 0, 14 do
local equipIndex = 106 + i -- 装备位索引
local btnX = startX
local btnY = startY + i * (btnHeight + spacing) -- 每个按钮纵向排列
-- 创建按钮
local buttonStr = "<Button|x=" .. btnX .. ".0|y=" .. btnY .. ".0|nimg=private/zbk/k.png|color=255|size=18>"
tk = tk .. buttonStr
-- 检查该装备位的装备是否存在
local equipCheckStr = "<$USEITEMNAME[" .. equipIndex .. "]>"
if getconst(actor, equipCheckStr) ~= "" then
-- 如果存在,添加对应的EquipShow控件
-- EquipShow放在按钮的正下方
local equipShowX = btnX
local equipShowY = btnY + btnHeight + spacing
local equipShowStr = "<EquipShow|x=" .. equipShowX .. "|y=" .. equipShowY .. "|width=" .. btnWidth .. "|height=" .. btnHeight .. "|index=" .. equipIndex .. "|showtips=1|reload=1|dblink=@tuoxia_" .. equipIndex .. ">"
tk = tk .. equipShowStr
end
end
-- 将整个容器添加到界面
addbutton(actor, 7, 10245, tk)
end
```
**代码说明:**
1. **循环处理**:使用`for i = 0, 14 do`循环15次,对应装备位106到120。
2. **动态计算**:
- `equipIndex = 106 + i` 得到当前循环的装备位索引。
- `btnY = startY + i * (btnHeight + spacing)` 让每个按钮在纵向上依次排列,避免重叠。
3. **装备检查**:使用`getconst(actor, "<$USEITEMNAME[" .. equipIndex .. "]>")`动态生成检查字符串,判断每个装备位是否有装备。
4. **控件添加**:
- 每个循环都先添加`<Button>`。
- 如果装备存在,再在按钮下方添加对应的`<EquipShow>`控件。
5. **链接区分**:`dblink=@tuoxia_` .. equipIndex 让每个装备位的双击链接都不同,方便你后续单独处理。
这样写就非常清晰了,如果要调整数量,只需要改循环范围就行。小仙,你试试看,有不懂的再问我哦!
← 返回问答库