You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

魔兽世界怀旧服Lua代码执行时消息发送量递增问题求助

问题根源

每次运行这段代码时,都会重新创建一个新的Frame并注册COMBAT_LOG_EVENT_UNFILTERED事件,之前创建的Frame不会被销毁,仍然在监听事件。每运行一次代码就多一个事件监听器,宠物施法成功时,所有监听器都会触发,每个监听器都会启动定时器发送消息,最终导致消息数量逐次递增。

修复方案

修改代码,确保只创建一次Frame和注册一次事件,避免重复绑定监听器:

-- 检查全局标记,避免重复初始化
if not _G.PetEmoteFrame then
    _G.petTarget = "their target" -- 宠物目标默认值

    -- 创建唯一监听Frame,用全局变量存储防止重复创建
    local frame = CreateFrame("Frame")
    _G.PetEmoteFrame = frame

    frame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
    frame:SetScript("OnEvent", function()
        local _, subEvent, _, sourceGUID, _, _, _, _, destName = CombatLogGetCurrentEventInfo()
    
        -- 仅处理宠物的施法成功事件
        if subEvent == "SPELL_CAST_SUCCESS" and sourceGUID == UnitGUID("pet") then
            if destName then -- 避免目标为空时覆盖全局变量
                _G.petTarget = destName
            end
        
            -- 延迟发送表情,确保游戏内宠物目标信息更新完成
            C_Timer.After(0.1, function()
                local petName = UnitName("pet") or "my pet"
                local petTarget = _G.petTarget

                local phrases = {
                    "commands " .. petName .. " to devour magic from " .. petTarget .. ". Good puppy!",
                    "orders " .. petName .. " to feast on the magic of " .. petTarget .. ". Well done!",
                    "directs " .. petName .. " to absorb magical energy from " .. petTarget .. ". Good job!",
                    "commands " .. petName .. " to siphon power from " .. petTarget .. ". Atta boy!"
                }

                SendChatMessage(phrases[math.random(#phrases)], "EMOTE")
            end)
        end
    end)
end
关键修改说明
  • 新增_G.PetEmoteFrame全局标记,确保代码多次运行时仅初始化一次监听逻辑
  • 将原PetCommandEmote函数的逻辑内嵌到定时器回调中,避免全局函数被重复定义
  • 所有初始化逻辑包裹在判断语句内,彻底杜绝重复创建监听器的问题

内容的提问来源于stack exchange,提问作者Boosticuff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 14:47:02