Why does look == 0 twice in a loop that ticks?

This code prints “look is 0” two times, then counts up. I then get one more play than I expect. Shouldn’t look be a different value after every time you tick?

live_loop :testLoop do
  puts "look is", look
  
  if look < 5
    play 60
    sleep 1
  else
    sleep 1
  end
  
  tick
end

The reason is that tick is designed to work well when iterating through rings. For example, if we write:

live_loop :test do
  puts (ring 1, 2, 3).tick
  sleep 1
end

Then we will see something similar to the following in the logs:

{run: 1, time: 0.0, thread: :live_loop_test}
 └─ 1
 
{run: 1, time: 1.0, thread: :live_loop_test}
 └─ 2
 
{run: 1, time: 2.0, thread: :live_loop_test}
 └─ 3
 
{run: 1, time: 3.0, thread: :live_loop_test}
 └─ 1
 
{run: 1, time: 4.0, thread: :live_loop_test}
 └─ 2

{run: 1, time: 5.0, thread: :live_loop_test}
 └─ 3

(and so on…).

Note here, that in order to print 1 the first time we step through the ring items, tick has to return 0 the first time. Otherwise, if the first time it was called it returned 1, we would skip the first ring item.

The idea here to make it do what you want is to call tick before you call look :slight_smile:

Hope that helps!

3 Likes