luamacroslogitechlogitech-gaming-software

Create toggle functionality for keyboard in LUA script (logitech G hub)


this will be my first post here. I am trying to create a script that works as a toggle using LUA the functionality I want is a single key "G1" which initiates a loop when pressed and breaks the loop when pressed again.

my code:

local msMakro = false
local safety = 0
function OnEvent(event, arg)
    OutputLogMessage("Event: "..event.." Arg: "..arg.."\n")
    
    --MS MAKRO--
    if (event == "G_PRESSED" and arg == 1) then
        OutputLogMessage("\nG1 Pressed \n")

        msMakro = not msMakro
        OutputLogMessage("msMakro = ")
        OutputLogMessage(tostring(msMakro))
        OutputLogMessage("\n")
    end
      
    while (msMakro and safety < 5) do
        PressAndReleaseKey("a")
        Sleep(math.random(1000, 1500))
        safety = safety +1
        OutputLogMessage("safety = ")
        OutputLogMessage(safety)
        OutputLogMessage("\n")        
    end
end

the following code does not allow to break the loop pressing the button again it will just queue the call and display it in the terminal once the while is exited on the safety condition

I've looked for similar problems but did not seem to find a solution that worked for this case


Solution

  • Assign "Back" action to the G1 key.
    "Back" action is the standard assignment for Mouse Button 4.
    So, now your G1 key acts as "Backward" mouse button, and you can monitor its state with IsMouseButtonPressed(4).

    local msMakro = false
    local safety = 0
    
    function OnEvent(event, arg)
        OutputLogMessage("Event: "..event.." Arg: "..arg.."\n")
        --MS MAKRO--
        if event == "G_PRESSED" and arg == 1 then
            OutputLogMessage("\nG1 Pressed \n")
            msMakro = not msMakro
            OutputLogMessage("msMakro = ")
            OutputLogMessage(tostring(msMakro))
            OutputLogMessage("\n")
            while msMakro and safety < 5 do
                PressAndReleaseKey("a")
                local tm = GetRunningTime() + math.random(1000, 1500)
                local prev_mb4 = true
                repeat
                    Sleep(10)
                    local mb4 = IsMouseButtonPressed(4)
                    if mb4 and not prev_mb4 then return end
                    prev_mb4 = mb4
                until GetRunningTime() > tm
                safety = safety +1
                OutputLogMessage("safety = ")
                OutputLogMessage(safety)
                OutputLogMessage("\n")
            end
        end
    end