---@diagnostic disable: undefined-global, unnecessary-if
-- 保存当前界面的引用
local currentParent = nil
local function main()
-- 如果界面已存在,先关闭它
if currentParent and not GUI:Win_IsNull(currentParent) then
GUI:Win_Close(currentParent)
c
这段代码有几个地方可以优化。我来帮你分析一下:
## 主要问题:
1. **事件注册位置不当**:在`main()`函数外注册事件,会导致每次调用模块时重复注册
2. **界面关闭逻辑冗余**:在事件回调中重复了main函数中的关闭逻辑
3. **事件注销不完整**:关闭按钮中只注销了一个事件,但没有清理其他事件
4. **变量作用域问题**:`currentParent`作为全局变量可能存在冲突
## 优化后的代码:
```lua
--@diagnostic disable: undefined-global, unnecessary-if
local currentParent = nil
-- 事件管理函数
local function registerEvents()
SL:RegisterLUAEvent(LUA_EVENT_REINLEVEL_CHANGE, "ReinLevelChange", function()
-- 刷新界面
if currentParent and not GUI:Win_IsNull(currentParent) then
GUI:Win_Close(currentParent)
currentParent = nil
end
main()
end)
end
local function unregisterEvents()
SL:UnRegisterLUAEvent(LUA_EVENT_REINLEVEL_CHANGE, "ReinLevelChange")
end
local function main()
-- 关闭旧界面
if currentParent and not GUI:Win_IsNull(currentParent) then
GUI:Win_Close(currentParent)
currentParent = nil
end
-- 创建新界面
local parent = GUI:Win_Create("Layout", 0, 0, 0, 0)
if GUI:Win_IsNull(parent) then
SL:Print("Error: Failed to create window")
return
end
currentParent = parent
GUI:LoadExport(parent, "4")
local ui = GUI:ui_delegate(parent)
GUI:Win_SetDrag(parent, ui.ImageView)
-- 关闭按钮事件
GUI:addOnClickEvent(ui.Button_1, function()
unregisterEvents() -- 先注销事件
GUI:Win_Close(parent)
currentParent = nil
-- 返回主界面
local module = SL:Require("dev.GUILayout.TopBut")
if module and module.main then
module.main()
end
end)
-- 开始转生按钮
GUI:addOnClickEvent(ui.Button_2, function()
SL:SendLuaNetMsg(4, 1, 0, 0, "开始转生")
end)
-- 注册事件(只在界面创建时注册)
registerEvents()
return parent
end
return { main = main }
```
## 优化说明:
1. **模块化事件管理**:将事件注册/注销封装成独立函数
2. **避免重复注册**:只在界面创建时注册事件
3. **统一关闭逻辑**:关闭按钮和事件回调都调用相同的关闭函数
4. **更好的内存管理**:确保界面关闭时清理所有相关资源
这样修改后,代码结构更清晰,避免了事件重复注册的问题,也更容易维护。如果还有不明白的地方,随时问我!