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

G502 Hero鼠标Lua脚本问题:M4按键启停循环失效

G502 Hero Lua脚本修复:M4按键启停循环问题

问题原因

你写的代码里,while循环是阻塞式的——一旦进入循环,整个脚本的执行线程会被这个循环占满,OnEvent函数根本没法结束,自然无法响应后续的M4按键事件。第二次按M4时,脚本接收不到这个触发信号,也就没法切换M4_pressed的状态来停止循环。

修复后的代码

local is_running = false

function OnEvent(event, arg)
    if event == "MOUSE_BUTTON_PRESSED" and arg == 4 then
        is_running = not is_running
        if is_running then
            -- 启动定时器,持续执行按键模拟
            SetTimer("SimulateKeyPress", 0)
        else
            -- 停止定时器,并确保按键被释放
            SetTimer("SimulateKeyPress", nil)
            ReleaseKey("2")
        end
    end
end

function SimulateKeyPress()
    PressKey("2")
    Sleep(math.random(60, 70))
    ReleaseKey("2")
    Sleep(math.random(60, 70))
end

代码说明

  • 用SetTimer实现非阻塞循环:定时器会在后台异步执行按键模拟逻辑,不会卡住OnEvent函数,确保脚本能随时响应M4按键的启停指令。
  • 启停切换逻辑:每次按下M4时,反转is_running的状态,根据状态决定启动或停止定时器。
  • 停止时释放按键:避免因为定时器突然停止导致按键"卡住"在按下状态。

原注释翻译

M4_pressed = not M4_pressed 
/* 这段代码的作用是:
    如果M4_pressed为true,就把它设为false;
    如果M4_pressed为false,就把它设为true;
*/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:52:14