How to get an input from a table?

Its a pretty straight foward question.

Here is my local script code:

local InputTypes = require(script.Modules.InputTypes)

local function findColorFromInput(input)
	for _,Color in pairs(InputTypes) do
		for Index,Input in pairs(Color) do
			if Input == input.Name then
				return tostring(Color)
			end
		end
	end
	
	return nil
end

UIS.InputBegan:Connect(function(input,gp)
	if not gp then
		local color = findColorFromInput(input)
		print(color) -- prints nil everytime!!! >:(
	end
end)

My module script code, aka InputTypes:

local module = {}

module.Red = {
	Enum.KeyCode.W.Name,
	Enum.KeyCode.Z.Name,
	Enum.KeyCode.ButtonA.Name
}

module.Yellow = {
	Enum.KeyCode.A.Name,
	Enum.KeyCode.X.Name,
	Enum.KeyCode.ButtonB.Name
}

module.Green = {
	Enum.KeyCode.S.Name,
	Enum.KeyCode.N.Name,
	Enum.KeyCode.ButtonX.Name
}

module.Blue = {
	Enum.KeyCode.D.Name,
	Enum.KeyCode.M.Name,
	Enum.KeyCode.ButtonY.Name
}

return module

I figured the .Name property would be best but Im not sure if its the way to go.

Edit for clarification: I need to get the name of the color but it prints nil. My use case would be something like pressing “D” and it printing “Blue”.

Shouldn’t it be

if Input == input.KeyCode.Name then

You need to give it the KeyCode’s name, that’s probably why it’s returning nil

Its working somewhat. It no longer prints nil but now it prints:
table: 0xe38fed8...
Theres a lot more random numbers and stuff. I think this is because tables have weird names like that, is there a way I can just make it print the name of the table its in? Example:
module.Blue would print "Blue"

EDIT: Just figured out that I needed to return “_” and not “Color”. Whoops :sweat_smile:

This isn’t guaranteed, but may help you.

UserInputService:GetStringForKeyCode(input) -- This should give you a string of the player's input.

Haha it’s okay! Trial and error is what gives results! If you have anymore issues don’t be afraid to make another post!

2 Likes

you do not need to use the names, you can use the objects directly

local InputTypes = {}

InputTypes.Red = {
	Enum.KeyCode.W,
	Enum.KeyCode.Z,
	Enum.KeyCode.ButtonA,
}

InputTypes.Yellow = {
	Enum.KeyCode.A,
	Enum.KeyCode.X,
	Enum.KeyCode.ButtonB,
}

InputTypes.Green = {
	Enum.KeyCode.S,
	Enum.KeyCode.N,
	Enum.KeyCode.ButtonX,
}

InputTypes.Blue = {
	Enum.KeyCode.D,
	Enum.KeyCode.M,
	Enum.KeyCode.ButtonY,
}

local function findColorFromInput(inputObject)
	for color, inputs in pairs(InputTypes) do
		for _, input in pairs(inputs) do
			if input == inputObject.KeyCode then
				return tostring(color)
			end
		end
	end

	return nil
end

UIS.InputBegan:Connect(function(input,gp)
	if not gp then
		local color = findColorFromInput(input)
		print(color)
	end
end)