Lua number comparison returns wrong result

42 Views Asked by At

I tried to use the hamerspoon package to write a timer as follows.

  local function startTimer()
    local totalSeconds = 5
    local i = 0
    local function onTimeout()
      i = i + .1
      local stopTimer = i == totalSeconds -- THIS BOOLEAN COMPARISSON RETURNS WRONG RESULT
      print('stopTimer:', stopTimer)
      print(i, totalSeconds, type(i), type(totalSeconds), 5 == 5.0)
      if stopTimer then 
        timer:stop()
      end
    end
    local timer = hs.timer.new(.1, onTimeout)
    timer:start()
  end

As you can see in the output below

  • stopTimer variable in above function is always false even for a comparisson of 5 == 5.0
  • The types of both variables are numbers
  • Simply printing 5 == 5.0 seems to show the correct result

enter image description here

stopTimer variable should be false when i is 5

0

There are 0 best solutions below