Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 10 years ago

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

Log in to vote
1
Answered by 10 years ago

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)
Ad

Answer this question