[SOLVED] Multiple Conditions on a single IF Statement

  1. What do you want to achieve? Keep it simple and clear!
    I want an if statement that can check for multiple conditions without typing if variable == 1 or variable == 3
  2. What is the issue? Include screenshots / videos if possible!
    I want to know if such a system is even possible to do.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried doing if variable == (1 or 2 or 3) but it only fires for 1.
2 Likes

You can try using Elseif which checks for alternate conditions

Ah I just red the top part of your post. You meant in one variable I’m stupid

You may try using tables.
Ex.

local variableCheck = {1,2,3}
if table.find(variableCheck,variable) then
   print("it exist")
end
4 Likes

That works perfectly for what I’m trying to achieve! Thank you!

Performance numbers b/c I was curious, not that it super matters for small number of comparisons.

A set lookup can do this in constant time, but it matters if your table is constant or if you’re creating it every time you do the condition:

local set = {[1] = true, [2] = true, [3] = true}
if set[variable] then
  print("exists")
end
benchmarks...

with find, separate table took 95.460500 ms
with find, inline table took 201.010300 ms
with set, separate table took 55.123100 ms
with set, inline table took 177.910000 ms
with ifs took 63.921800 ms

wait(1)


local function test(name, f)
	local start = os.clock()
	for i = 1, 1000000 do
		f()
	end
	local stop = os.clock()
	
	print(string.format("%s took %f ms", name, (stop-start)*1000))
	wait()
end

local find = table.find
local rand = math.random

local search = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

test("with find, separate table", function()
	local x = rand(1, 20)
	if find(search, x) then	end
end)

test("with find, inline table", function()
	local x = rand(1, 20)
	if find({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, x) then	end
end)

local set = {[1] = true, [2] = true, [3] = true, [4] = true, [5] = true, [6] = true, [7] = true, [8] = true, [9] = true, [10] = true}

test("with set, separate table", function()
	local x = rand(1, 20)
	if set[x] then end
end)
test("with set, inline table", function()
	local x = rand(1, 20)
	if ({[1] = true, [2] = true, [3] = true, [4] = true, [5] = true, [6] = true, [7] = true, [8] = true, [9] = true, [10] = true})[x] then end
end)

test("with ifs", function()
	local x = rand(1, 20)
	if x == 1 or x == 2 or x == 3 or x == 4 or x == 5 or x == 6 or x == 7 or x == 8 or x == 9 or x == 10 then end
end)
1 Like

Hmm, perhaps I might replace the table with a lengthy IF statement later in development, but for now code readability is much more important.

1 Like