Checking if a number is between two number in a table

Basically the title, I am trying to check if a number is between two value in a table.

local Numbers = {
	0,
	27.5,
	55,
	82.5,
	110
}
local GivenNumber = 30

---How do I tell the script the given number is between 27.5 and 55?
1 Like

Try this:

for i = 2, #Numbers do
if GivenNumber >= Numbers[i-1] and GivenNumber < Numbers[i] then
print("given number is between "..Numbers[i-1].." and "..Numbers[i]
end
end
local Numbers = {
	0,
	27.5,
	55,
	82.5,
	110
}
local GivenNumber = 101
local lowerIndex, upperIndex

for i = 1, #Numbers - 1 do
	if GivenNumber > Numbers[i] and GivenNumber < Numbers[i + 1] then
		lowerIndex = i
		upperIndex = i + 1
		break
	end
end

if lowerIndex and upperIndex then
	print("GivenNumber is between:", Numbers[lowerIndex], "and", Numbers[upperIndex])
else
	print("GivenNumber is not between any two numbers in the table, it is", GivenNumber)
end

Cool loop, nice and totally crazy looking.
But it works great both ways. (old school)

1 Like
targetNumber = 30

for i, v in numbers do
nextNumber = numbers[i + 1]
if nextNumber and (v <= targetNumber and targetNumber <= nextNumber) then
print(str(targetNumber).. " is between ".. str(v).. " and ".. str(nextNumber))
break
end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.