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

Checking for ALL keys instead of one?

In a localscript, I'm trying to code a weapon so that it'll activate a specific function when ANY letter key, even WASD, are pressed, and terminate the same function when the key is lifted. Is there any way I can do that W/O going through and assigning every individual key?

3 answers

Not tested, but should work:

local down

function AnyKeyPressed()
	while down do
		print("Any letter key was pressed!")
		wait(1)
	end
end

script.Parent.Selected:connect(function(mouse)
	mouse.KeyDown:connect(function(key)
		if key:match("%l") then
			-- we have a letter
			down = true
			AnyKeyPressed()
		end
	end)
	mouse.KeyUp:connect(function(key)
		if key:match("%l") then
			down = false
		end
	end)
end)

EDIT: Updated answer according to clarification from asker

5 comments

0

So where would I put my function in that? :P

0

Are you trying to execute a specific action for certain keys, or one action for any key?

0

One action for any key.

0

I've updated my answer accordingly

0

Thanks.

Yes, you can. I'll use "Activate" as function which is called when such key is pressed.

The idea behind this function is that we do a pattern match on the key to check if it is in the "character" group: lower case only, as upper cases don't matter.

game.Players.LocalPlayer:GetMouse().KeyDown:connect(function(key)
	if key and key:match("%l") then -- %l -> matches on lowercase letters. 
		Activate()
	end
end)

Please note that not all keys fire KeyDown: o and i for example are not passed, unless CameraType of CurrentCamera is set to scriptable.

2 comments

0

So would I replace "Activate()" with my function, or would I place it below it?

0

No, you can just define the Activate() function to the function which you wanted to call when a "letter key" has been pressed. (Who down voted my solution? Yes, it is the same solution as kenetec, but he ninja'd me...)

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