Why do loops make things stop under it?

Hi, so bassicly i made a function that runs a idle loop for a npc but i realized that the While loop ends everything under it even if it is in a function i remebered hearing that from a ByteBlox video, So how could i fix it?

1 Like

you can imagine the code gets executed line by line, so when the loop goes backwards, the code can’t just continue to outside of the loop. You would have to execute two things at the same time

If you want to execute two things at the same time then you can create a new thread with coroutines or task. Also note this isn’t true multithreading, which is also possible in another way in roblox

-- creates a new thread and immediately runs it
task.spawn(function()
  while true do -- this infinite loop won't block the code under it now
    task.wait(1)
    print("hello")
  end
end)

print("i can still run")

Coroutines can be more powerful in some cases but task is very simple
https://create.roblox.com/docs/reference/engine/libraries/coroutine

6 Likes

Yo thanks this works, i will look into coroutines more thank you