Lua script for g502 hero , loop until key press again

132 views Asked by At

I need Lua script start when I press M4 button on mouse press keys but I need this in loop until I press M4 again.

-- NOT HOLD - PRESS AGAIN --

here is my code;

local M4_pressed = false

function OnEvent(event, arg)
    if event == "MOUSE_BUTTON_PRESSED" and arg == 4 then
        M4_pressed = not M4_pressed
        while M4_pressed do
            PressKey("2")
            Sleep(math.random(60, 70))
            ReleaseKey("2")
            Sleep(math.random(60, 70))
        end
    end
end

this is my code but its not stopping on press again.


M4_pressed = not M4_pressed 
/*this means 
    if(M4_pressed = true){M4_pressed = false)}
    if(M4_pressed = false){M4_pressed = true)}
*/
1

There are 1 answers

3
ESkri On

You should write a function to poll the MB4 status while sleeping.
Transition of IsMouseButtonPressed(4) from false to true means MB4 is pressed for the second time.

local MB4_pressed, second_MB4_press

local function InterruptableSleep(ms)
   local tm_stop = GetRunningTime() + ms
   while not second_MB4_press and GetRunningTime() < tm_stop do
      Sleep(10)
      local MB4 = IsMouseButtonPressed(4)
      MB4_pressed, second_MB4_press = MB4, MB4 and not MB4_pressed
   end
end

function OnEvent(event, arg)
   --OutputLogMessage("event = %s, arg = %s\n", event, tostring(arg))
   if event == "MOUSE_BUTTON_PRESSED" and arg == 4 then
      MB4_pressed = not MB4_pressed
      if MB4_pressed then
         second_MB4_press = false
         repeat
            PressKey("2")
            InterruptableSleep(math.random(40, 90))
            ReleaseKey("2")
            InterruptableSleep(math.random(40, 90))
         until second_MB4_press
      end
   end
end