Heya. I’ve noticed my code is really messy, and filled with while loops. The problem with while loops is that you cannot have code under it, since it only plays after the loop is finished. If i put it in functions the lower ones wont run if theres a while loop in the function over it. How can i prevent while loops in functions or outside of functions cancelling lower code? Or is there any alternatives? Any help is appreciated.
If you want code to run seperately (in this case, you would want your while loops to run seperately), there are 2 main options:
My preferred way of doing it is to use task.spawn, as I feel like it is simpler.
It’s a fairly simple command, taking just the function to run seperately as well as any arguments to send to the function.
Here’s a (basic) example of how to use it:
print("Before")
task.spawn(function()
while true do
task.wait(1)
print("Looping")
end
end)
print("After")
Out of curiosity, what are these loops actually doing? You may be better off using events instead of loops, depending on the use case.
Coroutines and task.spawn as SeargeantAUS suggested could work. Events could also work here depending on how frequent your while loops run. Look into RunService?
The loops are often for checking if something is true
what does the loop actually do
The loop is checking if (variable) is (something), then running a function.
Is it a variable that you are checking, or is it the value of a particular object?
(If you could also please provide a sample of the code you have currently, then that will help)
The coroutines worked, but heres the code incase i should use events instead:
local chaseCheck = coroutine.wrap(function()
while CHASING_PLAYER == false do
task.wait(CHASE_CHECK_TIME)
local CHASE_CHANCE = math.random(1, CHASE_CHECK_CHANCE)
if CHASE_CHANCE == 1 then
chasePlayer()
end
end
end)
chaseCheck()
As it’s a local variable, there’s not really much in the way of events for you to use. Subsequently, loops are the way to go!
Polling also your doing here is not a great approach. It takes up resources since it still constantly checks for updates even though nothing may of changed. You can try an event-driven approach instead using bindable events (Signal class).
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.