Reputation: 653
I'm brand new to lua and LÖVE.
I am trying to do a simple counting of numbers with a small delay, so that the user can see the count happen (instead of the code simply counting and then displaying the finished count)
I have the following code:
function love.draw()
love.graphics.print("Welcome again to a simple counting sheep excercise.", 50, 50)
i = 20
ypos = 70
while i > 0 do
love.graphics.print("Number: " .. i .. ".", 50, ypos)
love.timer.sleep(1)
i = i - 1
ypos = ypos + 12
end
end
But when I run it, it just hangs for ~20 seconds and then displays the completed count. How do I make it pause briefly between each iteration? I suspect that the problem is that the draw function is called once, and so it completes all of its work before displaying.
Upvotes: 1
Views: 2925
Reputation: 9490
love.draw()
is called many times per second, so you shouldn't really sleep, because it causes the entire application to hang.
Instead, use love.update()
to update the state of the application based on the current time (or based on time delta).
For example, I would express what you're trying to do as follows:
function love.load()
initTime = love.timer.getTime()
displayString = true
end
function love.draw()
love.graphics.print("Welcome again to a simple counting sheep excercise.", 50, 50)
if displayString then
love.graphics.print("Number: " .. currentNumber .. ".", 50, currentYpos)
end
end
function love.update()
local currentTime = love.timer.getTime()
local timeDelta = math.floor(currentTime - initTime)
currentNumber = 20 - timeDelta
currentYpos = 70 + 12 * timeDelta
if currentNumber < 0 then
displayString = false
end
end
First I find the initial time, and then I calculate the number and the position based on the time difference from the initial time. The difference is in seconds, which is why I call math.floor
to make sure I get an integer.
Upvotes: 4