"or" does not seem to work in this case

the title might not make sense so let me try to explain what I mean.

So I have this script:

if input.KeyCode == (Enum.KeyCode.One or Enum.KeyCode.Two or Enum.KeyCode.Three) then
end

and the problem is that it only checks if the input.KeyCode is Enum.KeyCode.One and not the Enum.KeyCode.Two or Enum.KeyCode.Three

In order to fix this, I would have to do:

if input.KeyCode == Enum.KeyCode.One or input.KeyCode == Enum.KeyCode.Two or input.KeyCode == Enum.KeyCode.Three then
end

Is there a faster/easier way to do this?

You could have a dictionary of possible keys and look up the one pressed:

local keysToCheck = {
    [ Enum.KeyCode.One ] = true,
    [ Enum.KeyCode.Two ] = true,
    [ Enum.KeyCode.Three ] = true,
}

if keysToCheck[ input.KeyCode ] then
    -- do stuff
end

Edit: I missed off the square brackets around the keys initially. Thanks to the solution for pointing it out and correcting it.

4 Likes

To explain why or did not work. The way you did was basically telling the script

“Return the first one that is not nil/exists”

It checks Enum.KeyCode.One, it checks if it exists, and since it did, it will return that since it’s in brackets and completely ignore the other two

It’s the same principle as to how

local character = player.Character or player.CharacterAdded:Wait()

works, it checks if the Character is loaded already, and if it isn’t via player.Character returning nil, wait for the Character to be loaded/added

The best way you could probably simplify it is to do how @BanTech did by making a dictionary

2 Likes

This has been something that annoys me. In your case it is easy to have a better system, however in others it might be not.

One thing on type checking is that you can do:

function(arg: string | number)

And for the longest time I was trying to do this with if statements because I thought it was an actual thing.

I think this should be bringed to conditions in some form, it doesn’t need to use the |.

This gave me a Syntax error saying that
“expected } to close at { got =”

Wrap those keys into [] since they are enums:

local keysToCheck = {
	[Enum.KeyCode.One] = true,
	[Enum.KeyCode.Two] = true,
	[Enum.KeyCode.Three] = true
}

if keysToCheck[ input.KeyCode ] then
	-- do stuff
end
2 Likes

if you want to use conditions at runtime with if statements, then you can just do:

if typeof(arg) == "string" or typeof(arg) == "number" then
  -- Do something, since we know the arg is string | number
end

That’s why I want something like that.

if typeof(arg) == "string" | "number" then
    --very epic code
end

It’s wayy shorter.