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

Is using one function for multiple keys possible?

Asked by 7 years ago
Edited 7 years ago

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

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago

Of course.

You can use any objects1 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. 

0
Thanks. Others told me how to do it in chat too, thanks to them too :) superalp1111 662 — 7y
Ad

Answer this question