Compare two values (numbers) with a tolerance

I would like to compare two number values stored as variables with a specified tolerance

I have searched on the wiki and the dev hub and cant find what i am looking for.

The number values are are objects stored in the explorer server side

I am trying to check a stopwatch time and compare it to a server stopwatch but I think I will
have to build in some tolerance for safety.

I will not know the actual values of these number Values

this is roughly what i am after I just dont know the maths to calculate the result

    Local timeOne = 420 --Actual time will be unknown
    Local timeTwo = 435 --Actual time will be unknown
    If timeOne == timeTwo +/- 20 then
        Print ("Valid Time")
          Print ("Invalid Time")
-- This is an example Lua code block

This is just dummy code, just to illustrate my point

Thanks for any help or advice.

local timeOne = 420 --Actual time will be unknown
local timeTwo = 435 --Actual time will be unknown

if timeOne >= timeTwo - 20 or timeOne <= timeTwo + 20 then
    print ("Valid Time")
    print ("Invalid Time")

You could use >= and <=


if timeOne >= timeTwo - 20 and timeOne <= timeTwo + 20 then

You can use math.clamp():

if math.clamp(timeOne, timeTwo - 20, timeTwo + 20) == timeOne then

There’s no one way to do this, and there’s even more than these two.


Thanks for the reply’s
I’ve had a long day my brain was just ‘hanging’

1 Like
if math.abs(timeOne - timeTwo) == 20 then

Wouldn’t this be the exact behavior you’re trying to achieve? Unfortunately Lua doesn’t offer a +/- capability. It gets the value of the two times subtracted from one another, the absolute value is then determined which just removes any negative sign (if present) and then this resulting value is compared with an integer value of 20.