1
votes

I'm writing a script in LUA/logitech scripting API. The script should perform the following:

  • mouse key 4 switch on/off the script
  • mouse key 5 switch from one feature to other ( force move and autoattack )

    The code is the follow:
    forceMove = false
    on = false
    function OnEvent(event, arg)
        --OutputLogMessage("event = %s, arg = %s\n", event, arg);
        if IsMouseButtonPressed(5) then
            forceMove = not forceMove
            while(on) do
                if(forceMove) then
                    ForceMove()
                else
                    StartAttack()
                end
            end
        ReleaseMouseButton(5)
        end
    
        if IsMouseButtonPressed(4) then
            on = not on
            ReleaseMouseButton(4)
        end
    end
    
    function StartAttack()
        PressAndReleaseMouseButton(1)
        Sleep(1000)
    end
    
    function ForceMove()
        MoveMouseWheel(1)
        Sleep(20)
        MoveMouseWheel(-1)
    end
    

    but once in game,if i activate the script with mouse button 4, i get stuck in "force move" mode, and "auto attack" mode never works. Can't figure why.

  • 1

    1 Answers

    2
    votes

    When you press mouse button 5, you activate the 'force move' mode. If the 'on' mode is simultaneously enabled, you result in a infinite loop:

    while(on) do
        if(forceMove) then
            ForceMove()
        else
            StartAttack()
        end
    end -- loops regardless of mouse buttons
    

    You will stay here forever, regardless of the mouse buttons you press. You need to move to executing code out of the mouse event handler. The handler should only update values like forceMove, another function is needed to carry out the action. In these function, you only do ONE step, not many. Then you check again for pressed mouse buttons, carry out the actions and so on. Code example:

    function update()
        if IsMouseButtonPressed(4) then
            on = not on
        end
        if IsMouseButtonPressed(5) then
            forceMove = not forceMove
        end
    end
    
    function actions()
        if on then
            if forceMove then
                ForceMove()
            end
        end
    end
    

    How to put it together: You have to use some kind of loop, but ideally the game engine should do this for you. It would look something like this:

    local is_running = true
    while is_running do
        update()
        actions()
    end
    

    Now, if you press a button, you save the current state in some global variables which are accessed both by update and actions. The functions get called every cycle (which can be the calculation of one frame). Assuming you don't press any further buttons, update() does nothing, so forceMove and on remain the same. This way, you have a continuous movement without a loop in action().