Adafruit VL6180X, non-blocking code (revisited... )

Hi!

I came across a post that describes exactly what I need, but unfortunately it´s almost two years old, so I´m not allowed to ask in that thread below anymore....

https://forum.arduino.cc/index.php?topic=566769.0

I´m no expert coder, and studying it before implementing inside my code, I didn´t understand a part of the code the user J-M-L posted, to create a new readRange function on the Adafruit´s VL6180X library into a non-blocking code, using a Switch Statement rather than While´s...

The new function is called readRangeNoWait, and everytime the new-function (readRangeNoWait) is called, it resets the _range_state variable to 0, before starting to check the state.

So how would the state change, if it´s always set to 0 when the function is called?

Should the _range_state variable be declared outside the function first, like globally? and inside the function it would only change depending on what each state does (and eventually change the _range_state value) ?

I´ll post the code J-M-L posted below here:

boolean Adafruit_VL6180X::readRangeNoWait(uint8_t &range)
{
  static uint8_t _range_state = 0; // 0 = Idle. 1 = read requested, waiting for device to be ready. 2 = trigger read. 3 = waiting for range to be avail. 4=data is there
  static boolean dataReady;

  switch (_range_state) {
    case 0: // initiate a read
      dataReady = false;
      _range_state = 1;
      break;

    case 1: // wait for device to be ready for range measurement
      if ((read8(VL6180X_REG_RESULT_RANGE_STATUS) & 0x01)) _range_state = 2;
      break;

    case 2:// Start a range measurement
      write8(VL6180X_REG_SYSRANGE_START, 0x01);
      _range_state = 3;
      break;

    case 3:// wait for data to be available, Poll until bit 2 is set
      if ((read8(VL6180X_REG_RESULT_INTERRUPT_STATUS_GPIO) & 0x04)) _range_state = 4;
      break;

    case 4:// read & cleanup, flag data is there
      range = read8(VL6180X_REG_RESULT_RANGE_VAL);      // read range in mm
      write8(VL6180X_REG_SYSTEM_INTERRUPT_CLEAR, 0x07);      // clear interrupt
      _range_state = 0; // go back to Idle state
      dataReady = true;
      break;

    default: // should not happen!
      break;
  }
  return dataReady;
}

And it´s used this way in the loop section:

uint8_t aRange;

...

// somewhere in the loop()

if (VL6180X.readRangeNoWait(aRange)) {
 // data ready, aRange is set with the right value

} else {
 // go do something else as the data was not ready

}