Use while true do loop?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
RealJace
Prole
Posts: 3
Joined: Mon Dec 06, 2021 3:26 pm

Use while true do loop?

Post 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)
MrFariator
Party member
Posts: 548
Joined: Wed Oct 05, 2016 11:53 am

Re: Use while true do loop?

Post 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.
Last edited by MrFariator on Tue Dec 14, 2021 10:42 am, edited 3 times in total.
User avatar
Nikki
Citizen
Posts: 86
Joined: Wed Jan 25, 2017 5:42 pm

Re: Use while true do loop?

Post 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 ;)
User avatar
zorg
Party member
Posts: 3465
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Use while true do loop?

Post 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
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 2 guests