How to efficiently detect input?

Lets say I have a list filled with keyCodes.

local keys = {

      Move1 = "One",
      Move2 = "Two",
      Move3 = "Three",
      Move4 = "Four",
      Move5 = "Five"

}

If I now would like to detect if one of those keys is pressed, would it be better (performance-wise) to go through the list using a for-loop

for i,key in pairs(keys) do
	if pressedKey == Enum.KeyCode[key] then
		
	end
end

or using multiple or statements:

if pressedKey == Enum.KeyCode[keys.Move1] or pressedKey == Enum.KeyCode[keys.Move2] or ...
	
end

?

UserInputService.InputBegan:Connect(function(io, gameProcessed)
   -- do stuff
end)
2 Likes

Did you even have a look at my question? Lol

Performance isn’t/shouldn’t even be on the table here – this is more of an ergonomics question than efficiency question. elseif chains aren’t necessarily a performance issue, but think of ergonomics.

2 Likes

You could just do this:

UserInputService.InputBegan:Connect(function(io, gameProcessed)
   local inputs = {
       [Enum.KeyCode.One] = function(...)
          -- do stuff
       end
   }

   if inputs[io.KeyCode] then
      inputs[io.KeyCode]()
   end
end)

Yes @HugeCoolboy2007’s solution is definitely one I’ve worked with before. However, I would bring the table of input outside the bound function. Also, if you want to get more advanced with it, you could set up a hierarchy of input tables like:

local uis = game:GetService("UserInputService")
local InputList = {
   Began = {
      [Enum.KeyCode.One] = function(...)
         
      end
   },
   Changed = {
   
   },
   Ended = {
      [Enum.KeyCode.One] = function(...)
         
      end
   }
}

uis.InputBegan:connect(function(io, gp)
   if not gp then
      if InputList.Began[io.KeyCode] then
         InputList.Began[io.KeyCode]()
      end
   end
end

uis.InputEnded:connect(function(io, gp)
   if not gp then
      if InputList.Ended[io.KeyCode] then
         InputList.Ended[io.KeyCode]()
      end
   end
end

This solution wouldn’t always be the most elegant or easy to work with depending on the specific context of your use like @sjr04 was saying. Consider the ways in which you need to detect input for your specific context and then formulate a system from there.

2 Likes