Reputation: 3636
I have a Lua script that works on Logitech G-Hub, and activates on the G4 key being pressed. It looks a bit like this:
function OnEvent(event, arg)
if (event == "G_PRESSED" and arg == 4) then
PressKey("s")
Sleep(200)
PressKey("lctrl")
Sleep(300)
...
end
end
It goes on to do a lot more. Anyway, I need it to stop doing its whole thing once the G4 key is released. So something like:
function OnEvent(event, arg)
if (event == "G_PRESSED" and arg == 4) then
PressKey("s")
if (event == "G_RELEASED" and arg == 4) then
return
end
Sleep(200)
if (event == "G_RELEASED" and arg == 4) then
return
end
PressKey("lctrl")
if (event == "G_RELEASED" and arg == 4) then
return
end
Sleep(300)
if (event == "G_RELEASED" and arg == 4) then
return
end
end
end
Now obviously, this is not going to work. Just giving an example. I need some sort of event listener inside the first if statement checking if the G4 button has been pressed.
Is it possible to have the function immediately terminate once the button is released, such that future commands do not execute?
Upvotes: 2
Views: 889
Reputation: 1928
You can use polling of key/button statuses inside a long running script to exit it immediately.
First, bind "Forward" action to physical key G4.
"Forward" is the default action for mouse button 5, so Windows will see your G4 press as if it was mouse button 5 press.
Second, set the script:
local function ShoudExitNow()
-- Exit when mouse button 5 is pressed
return IsMouseButtonPressed(5)
end
local function InterruptableSleep(ms)
local tm = GetRunningTime() + ms
repeat
-- Check exit condition every 10 ms
-- A human is unable to press and release a key faster than 30 ms, so 10 ms is enough for polling
Sleep(10)
if ShoudExitNow() then return true end
until GetRunningTime() >= tm
end
function OnEvent(event, arg)
if event == "G_PRESSED" and arg == 4 then
PressKey("s")
if InterruptableSleep(200) then return end
PressKey("lctrl")
if InterruptableSleep(300) then return end
...
end
end
Upvotes: 1