05-03-26

Interruptible Macro with Cancel Key

Create interruptible hardware input macros with this Lua script for Rebind. Define a sequence of actions and use a cancel key to stop the macro mid-execution. Customize hotkeys and the macro sequence

rebindlua scriptmacrointerruptiblecancel keyhardware inputscript

Question

Interruptible macro with cancel key

Rebind AI

luau
-- rebind: min_sdk=0.1.0
-- rebind: name=Interruptible Macro

local cfg = UI.Schema({
    start_key = UI.Keybind("F9", { label = "Start Macro" }),
    cancel_key = UI.Keybind("Escape", { label = "Cancel Key" }),
})

-- Define your macro sequence here
local macro = {
    { action = "press", code = "A", holdMs = 50, delay = 100 },
    { action = "press", code = "Tab", holdMs = 30, delay = 150 },
    { action = "type", text = "Hello World", charDelay = 50, delay = 100 },
    { action = "press", code = "Enter", holdMs = 50, delay = 200 },
}

local playbackHandle = nil

function OnDown(key)
    if key == cfg.start_key then
        if playbackHandle and playbackHandle:IsPlaying() then
            UI.Notify("Macro already playing", "warning")
            return false
        end
        
        playbackHandle = Macro.Play(macro, 1.0, "replace")
        UI.Notify("Macro started", "info")
        return false
    end
    
    if key == cfg.cancel_key then
        if playbackHandle and playbackHandle:IsPlaying() then
            playbackHandle:Stop()
            UI.Notify("Macro cancelled", "warning")
            return false
        end
    end
    
    return true
end

function OnStop()
    if playbackHandle and playbackHandle:IsPlaying() then
        playbackHandle:Stop()
    end
end

function OnBlur()
    if playbackHandle and playbackHandle:IsPlaying() then
        playbackHandle:Stop()
    end
end

This script demonstrates an interruptible macro with a cancel key:

Key features:

  • start_key (F9) plays the macro; pressing it again shows a warning if already playing
  • cancel_key (Escape) stops the macro mid-sequence
  • The macro sequence is defined in the macro table with actions like press, type, and delays
  • playbackHandle:IsPlaying() checks if the macro is currently executing
  • playbackHandle:Stop() immediately halts playback
  • Cleanup in OnStop and OnBlur prevents macros from leaking when the script unloads or the window loses focus

Customization:

  • Edit the macro table to define your own sequence
  • Change start_key and cancel_key to your preferred hotkeys
  • Adjust the speed with Macro.Play(macro, speedFactor) where 1.0 is normal

Learn more: