Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I make a KeyDown function using PlayerMouse and defining the key with a table?

This is basically the script:

local keys={
"q",
"e",
"r"
}
plr=game.Players.LocalPlayer
mouse=plr:GetMouse()
mouse.KeyDown:connect(function(key)
if key==keys[1] then
functiona()
elseif key==keys[2] then
functionb()
elseif key==keys[3] then
functionc()
end
end)

1 answer

✓ Accepted answer

Your original script, while technically correct, can be improved to make it easier to maintain. Instead of hardcoding the keys and the functions that are executed when they're pressed, you could do something like this:

local keys = {}

local function connectKey(key, onpress)
    keys[key] = onpress
end

mouse = game.Players.LocalPlayer:GetMouse()
mouse.KeyDown:connect(function(key)
    for storedKey, onpress in pairs(keys) do
        if storedKey == key then
            onpress()
            return
        end
    end
end

This stores a function in the keys table, indexed by the key it is linked to. To add a new keybind, just call connectKey. For example, to add a new keybind that executes on 'a', you'd use:

connectKey("a",  function() print("A was pressed!") end)

This discussion is preserved as it was. New answers, comments, and votes are closed.