A common occurrence I see when lurking or assisting in help channels for Roblox Lua is people using the old, deprecated, mouse functions for detecting keyboard input.
The main reason that this happens (as far as I know) is because of free models, and outdated tutorials. While there is nothing wrong with looking at free models, you should always keep in mind that there is a high chance that the models you are looking at might not have the most up-to-date code. Since these functions are deprecated, it is best to know how to write up-to-date keyboard handling code.
Keyboard handling is primarily done through two services now. ContextActionService (CSA), and UserInputService (UIS). This will only discuss UserInputService. It should be noted that these two services are different, but UserInputService is, more often than not, the "correct" solution to most of the problems I see posted.
So, let us try to convert this disaster:
local Player = game:GetService("Players").LocalPlayer local Mouse = Player:GetMouse() Mouse.KeyDown:Connect(function(pressedKey) if pressedKey == "a" then print("A was pressed!") end end)
Into something more in-line with modern code.
UserInputService exposes two events that will be of use to us here. InputBegan, and InputEnded. Both of these events return an InputObject which contains a property that specifies the KeyCode of the pressed key. This will allow you to determine the key that was pressed when using InputBegan, and the key that was released in InputEnded. This is an example of how to use UserInputService to detect when the "A" key is pressed:
local UserInputService = game:GetService("UserInputService") local Player = game:GetService("Players").LocalPlayer UserInputService.InputBegan:Connect(function(pressedKey) if pressedKey.KeyCode == Enum.KeyCode.A then print("A was pressed!") end end)
Most of what this comes down to is simply comparing the KeyCode property of the InputObject, which in this case is represented by the pressedKey parameter, to an Enum representing the letter A. You can follow the same logic shown in this example, to basically any other key that you can find on your keyboard. You can find a list of each key's Enum on this page.