Detecting if player pressed backspace in a TextBox (plugin)

Hey everyone!
I’m working on a command executor plugin for roblox, for which I’m creating a small script editor. Here, I want to autocomplete closing parentheses and quotes, which I’m doing with this function that runs on TextBox:GetPropertyChangedSignal(“Text”):

local function onTextChanged()
    if inputIgnoreChange then return end
    local lastChar = input.Text:sub(input.CursorPosition - 1, input.CursorPosition - 1)
    
    inputIgnoreChange = true

    if lastChar == "(" then
        input.Text = insertCharIntoString(input.Text, ")", input.CursorPosition)
        input.CursorPosition -= 1
    elseif lastChar == '"' then
        input.Text = insertCharIntoString(input.Text, '"', input.CursorPosition)
        input.CursorPosition -= 1
    end

    task.wait(.05)
    inputIgnoreChange = false
end

This works fine, except that when the user presses backspace and the cursor returns to a ( or " character, it will autocomplete those unintentionally. Therefore, I need to be able to detect when the player presses Backspace in order to prevent this autocomplete from happening. This cannot be done using UserInputService, since InputBegan events are blocked when a TextBox is focused for plugins.
Any help is greatly appreciated!

It would probably make more sense for you to check whether the last key has an autocomplete handle instead of checking whether to ignore autocomplete handles on a specific key.

local previousText = input.Text
local function onTextChanged()
   local currentText = input.Text
   if string.len(currentText) <= string.len(previousText) then
      return
   end
   --After this point, we know that text has been added to the field. Can process it, and invoke a handle accordingly

   previousText = input.Text --Finally, updated cached variable so it's accurate for the next call
end
1 Like

Thanks, not sure why I didn’t think of this myself!