05-03-26

Last-Key-Wins SOCD Cleaner for WASD

This Lua script implements a last-key-wins SOCD cleaner for WASD input on your hardware. It ensures that when conflicting inputs are detected, the most recently pressed key takes priority, improving p

rebindlua scriptsocdlast key winswasdinputhardware input

Question

Write me an SOCD cleaner with last-key-wins for WASD

Rebind AI

Here is a last-key-wins SOCD cleaner:

lua
-- rebind: name=SOCD Last Key Wins
-- rebind: tick_rate=8000

local held = {}
local virt = {}

local OPPOSITE = { A = "D", D = "A", W = "S", S = "W" }

local function setVirt(key, state)
    if virt[key] == state then return end
    virt[key] = state
    if state then HID.Down(key) else HID.Up(key) end
end

local function resolve(a, b)
    if held[a] and held[b] then
        -- both held: last pressed wins
        setVirt(a, false)
        setVirt(b, true)
    elseif held[a] then
        setVirt(a, true)
        setVirt(b, false)
    elseif held[b] then
        setVirt(a, false)
        setVirt(b, true)
    else
        setVirt(a, false)
        setVirt(b, false)
    end
end

function OnDown(code)
    if not OPPOSITE[code] then return true end
    held[code] = true
    if code == "A" or code == "D" then resolve("A", "D") end
    if code == "W" or code == "S" then resolve("W", "S") end
    return false
end

function OnUp(code)
    if not OPPOSITE[code] then return true end
    held[code] = false
    if code == "A" or code == "D" then resolve("A", "D") end
    if code == "W" or code == "S" then resolve("W", "S") end
    return false
end

function OnBlur()
    for key, _ in pairs(virt) do setVirt(key, false) end
    held = {}
end

This implements last-key-wins SOCD cleaning at 8kHz. When both A+D or W+S are held, only the most recently pressed key registers. Releasing one immediately activates the other.

Learn more: