0
votes

I'm not familiar with Lua, just writing some lua script for logitech mouse to play game.....

Here is what I expected: when I press some key on mouse, it began to press '1' on the keyboard, and when I press the mouse key again, it just stop.

And here is what I've tried: I use a global flag to keep track of the switch, but it won't stop once begin....I don't know how lua handle events, and I suppose global flag is not a good idea. So any better way to do this?

here is the code:

on = 0
cd = 50

function shift_example() 
    while on do
        PressAndReleaseKey("1")
        Sleep(cd)
    end 
end


function OnEvent(event, arg) 
    OutputLogMessage("event = %s, arg = %s\n", event, arg) 
    if (event == "MOUSE_BUTTON_PRESSED" and arg == 5 and on ==0) then 
        OutputLogMessage("set on = true\n") 
        on = 1
        shift_example() 
    end 
    if (event == "MOUSE_BUTTON_PRESSED" and arg == 5 and on == 1) then 
        OutputLogMessage("set on = false\n") 
        on = 0
    end 

end
1
You say it begins and stops and in the next sentence you say it begins and won't stop. So what is it now? - Piglet
@Piglet sorry for the confusion. What I expect is it can begins and stops when I press the mouse key. And the last sentence is the actual behavior of my script. I've updated my question - Ziqi Liu

1 Answers

0
votes

Your script is busy running the loop. It will not process any events while running the loop.

Poll the button state every time using IsMouseButtonPressed(1) within your loop and break the loop on the next 0-1 transition. Your updaterate is of course limited by the delay.

Replace longer delays by small loops that frequently check the button state with short delays.

Edit: added example

I don't have any Logitech hardware so I can't test it. This code should start spamming Key 1 once you click mouse button 5 and stop once you click it again. It's a very simple approach that does not store any button states. Instead it just does something while the button is pressed and then does the same thing until the button is pressed. A second click will cause the second loop to end and you can process new events.

function Button5Loop()
   -- we are here because the button was pressed so it should still be pressed
   -- so we can start doing something as long as the button is pressed
   -- but this time we check the button state in every loop cycle
   while IsMouseButtoPressed(5) do
    PressAndReleaseKey("1")
    Sleep(50)
   end
   -- the button not pressed anymore so it has been released
   -- so we continue spamming in a second loop
   -- until the button is pressed again
   repeat
     PressAndReleaseKey("1")
     Sleep(50)
   until IsMouseButtonPressed(5) 
end

function OnEvent(event, arg) 
    OutputLogMessage("event = %s, arg = %s\n", event, arg) 
    -- mousebutton 5 has been pressed
    if event == "MOUSE_BUTTON_PRESSED" and arg == 5 then 
        Button5Loop() 
    end
end