Code: Select all
local d = 0
local z = 0.2
function love.load()
return nil
end
function love.update()
d = d + z
if d == 2 then
z = -0.2
end
print(d)
end
function love.draw()
return nil
end
And well, it ain't working. The console logs show that the program skips the "reverse" moment and just keeps increasing d by 0.2 ad infinitum.
For investigation purposes, I tried changing the if d==2 to if d >= 2. And the console log revealed the problem immediately: the program kept increasing d up to 2, then it went to 2.2, and only after that it started decreasing it.
And now I'm looking at the code like an idiot and just can't understand what a hell is going on. Suppose that d is at 1.8. On the next frame, it's going to be incremented by 0.2 and become equal to 2. Immediately after that, it's gonna run the if d == 2 test, which will return true because it's already 2 at this moment. Which will immediately set z to -0.2. By the start of the next frame, d is gonna be equal to 2, and z will be equal to -0.2, which means that it SHOULD start going down immediately.
So what is this? Is Lua "asynchronous" or something like that, and starts running the next frame before it has finished the previous one? Or does it not actually update variable before the next frame begins?
So far the only way I can achieve the desired effect is by setting if d >= 1.8. In this case, yes - it will go to 1.8, then up one more step to exactly 2, and then go down. However, it just sounds like a bad coding practice, especially since I need to keep z variable as adjustable.