Page 1 of 1

Use while true do loop?

Posted: Tue Dec 14, 2021 10:20 am
by RealJace
Hello devs!
So I was thinking about this for long time, I tried using while true do loop for spawning collectibles, but every time I create while true do loop game crashes, so How do I fix that (PS : Yes I added timer.sleep)

Re: Use while true do loop?

Posted: Tue Dec 14, 2021 10:37 am
by MrFariator
A while loop will loop as long as the condition holds true. On the other hand, love.timer.sleep will halt the execution of the thread it's run on. If you put those two together, without a way for the while loop to exit, you have created an infinite loop that will also hang the thread due to all the calls to love.timer.sleep. That'll promptly crash on basically any system.

To break out of a while true loop, you can use either the 'return' keyword (exits the current scope and optionally returns values), or 'break' (exits the current loop). Eq:

Code: Select all

local counter = 0
while true do
  counter = counter + 1
  if counter > 10 then
    break 
  end
end
As far as love.timer.sleep goes, you don't really want to use it on the main thread, as it will hang execution like how the wiki warns about it.

Re: Use while true do loop?

Posted: Tue Dec 14, 2021 10:38 am
by Nikki
If you could post some code that might help in pinpointing your issue ?

my guess is since you said

Code: Select all

while true do
you never break from the loop and thus it ends up running until infinity or until your program crashes ;)

Re: Use while true do loop?

Posted: Tue Dec 14, 2021 1:11 pm
by zorg
Alternatively, you get used to löve giving you an update function that's already part of an "infinite" loop, and implement a timer into that, probably based on MrFariator's code example:

Code: Select all

local accumulator = 0
function love.update(dt)
  accumulator = accumulator + dt
  if accumulator > 10.0 then
    -- do something after 10 seconds
    accumulator = accumulator - 10.0 -- reset timer
  end
end