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

Is using one function for multiple keys possible?

Well, I saw tip of the day "Writing one function is quicker than writing the same code twice. (Credit to CodeTheorem)" and I remembered a question that I asked to myself before, and I still wonder it. Is it possible to use only one function for multiple keys for keypress events?(Hope typed that right)

To be more explanatory let's say we have a LocalScript which prints another thing as we type another key, let me give an example:

function onKeyPress(inputObject, gameProcessedEvent)
	if inputObject.KeyCode == Enum.KeyCode.One then
		print("Hello! Whazzup?")
	elseif inputObject.KeyCode == Enum.KeyCode.Two then
		print("I'm superalp1111")
	elseif inputObject.KeyCode == Enum.KeyCode.Three then
		print("And this is an example!")
	end
end
 
game:GetService("UserInputService").InputBegan:connect(onKeyPress)

Is it possible to call a function to get string to print from an array to print as player presses a key and we use that KeyCode as an index? Like, you know, converting an Enum.Keycode to a number. Maybe like:

a = {"Hello! Whazzup?","I'm superalp1111","And this is an example!"}
function onKeyPress(inputObject, gameProcessedEvent)
	print(a[tonumber(inputObject.KeyCode)]) --Just an example of the thing I want don't rage on me mkay?
end
 
game:GetService("UserInputService").InputBegan:connect(onKeyPress)

1 answer

✓ Accepted answer

Of course.

You can use any objects[^1] that you want as keys of a dictionary.

local messageByKey = {
	[Enum.KeyCode.One] = "Hello!",
	[Enum.KeyCode.Two] = "Blah",
	[Enum.KeyCode.Three] = "Three",
	-- etc
}

function onKeyPress(keycode)
	-- (I'm skipping some stuff here in handling an event --
	-- do what you need to in order to get the keycode)
	
	local message = messageByKey[keycode]
	if message then
		-- there IS a message in the dictionary for this key
		print(message)
	else
		-- this key isn't listed in the dictionary
		print("Idk what to do for that key")
	end
end

[^1]: It isn't wise to use some objects like Vector3 or CFrame. Dictionary keys are looked up by reference; two Vector3s or CFrames can be a different "object" but have the same value. Enums, however, are guaranteed to be the same object if they have the same value, so they're usable as keys.

1 comment

0

Thanks. Others told me how to do it in chat too, thanks to them too :)

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