It’s kinda hard to explain, but im trying to do like, lets say im checking if a variable named test is equal to 1 or 2, is it possible to do this without doing if test == 1 or test == 2
I tried this:
local test = "2"
if test ~= ("1" and "2") then
print("Its not equal to either.")
print(test)
else
print("Its equal to one of them.")
print(test)
end
local allowedValuesMap = {
["1"] = true,
["2"] = true
}
local test: string = "1"
if allowedValuesMap[test] then
print("Passed the test!")
else
print("Didn't pass the test.")
end
I usually user table.find for bigger lists, you can do something like this:
local test = "2"
if not table.find({"1", "2"}, test) then
print("Its not equal to either.")
print(test)
else
print("Its equal to one of them.")
print(test)
end
it might not be the most eficient solution but it works
local test = "2"
if test ~= "1" and test ~= "2" then
print("Its not equal to either.")
print(test)
else
print("Its equal to one of them.")
print(test)
end
Just to explain the reason this happens; it is because the way ternary operators work in Lua. Everything that is not false or nil is considered true, so "1" would be truthy.
If you use the and operator, it will check the first value for truthiness and if it is so, it will use the second value.
local value = "1" and "2"
print(value) -- 2
So, when you use ~=, what’s really happening in your clause is:
local value = "1" and "2"
local one = "1" ~= value -- true
local two = "2" ~= value -- false
That’s why you must use (test ~= 1) or (test ~= 2). Both statements will coerce into true or false and then it checks if either are true to pass.