你可以使用 `for` 循环来简化这5个按钮的事件绑定。根据浮生梦老师前端课程内容,可以这样写:
```lua
for i = 1, 5 do
local button = GUI:getChildByName(ui, "Button_" .. i)
if not GUI:Win_IsNull(button) then
GUI:addOnClickEvent(button, function()
SL:print(config[i])
end)
end
end
```
**代码说明:**
1. `for i = 1, 5 do` - 循环1到5
2. `GUI:getChildByName(ui, "Button_" .. i)` - 动态获取按钮组件
3. `GUI:Win_IsNull(button)` - 检查按钮是否存在
4. `SL:print(config[i])` - 动态打印对应的config值
**注意事项:**
- 确保 `ui` 对象已经正确获取(通过 `GUI:ui_delegate` 或 `GUI:getui`)
- 确保 `config` 表已经定义且包含1-5的索引
- 如果按钮ID不是连续的,可以使用数组存储ID名:
```lua
local buttonNames = {"Button_1", "Button_2", "Button_3", "Button_4", "Button_5"}
for i, btnName in ipairs(buttonNames) do
local button = GUI:getChildByName(ui, btnName)
if not GUI:Win_IsNull(button) then
GUI:addOnClickEvent(button, function()
SL:print(config[i])
end)
end
end
```
这样代码更清晰,也便于维护。