Yes, but not in the same way you're trying to do. Loops won't execute the next line of code until whatever condition they're given is met. Therefore, using an infinite while true statement will run the loop forever, never executing the code after the loop's block, meaning your function play was never evaluated.
Synopsis
You typically don't want while loops running in different places (for this to even be possible, coroutines would be involved, which is a whole other story). Whatever it is you're trying to do, there's probably a much better solution for it.
Answer
To answer your question, though, you would want the condition of your while loop to be mutable (not constant). That way, you can change the variable the while loop is using as a condition, to terminate the loop next iteration. Example:
local running = true
spawn(function()
while running do
print("Loop is running")
wait()
end
print("Stopped running")
end)
local function stopRunning()
running = false
end
wait(1)
stopRunning()
The code above is just for practice, I don't recommend using it in any project you're working on. However, this would be the answer to your question. If need help understanding anything, just let me know.
Edit:
Adding a "pause and play" mechanic
Creating a "pause and play" mechanic to a loop, would implement coroutines. You don't have to use them directly, but they're being used one way or another (with other functions like spawn), so I'm going include them in my example.
local create = coroutine.create
local resume = coroutine.resume
local yield = coroutine.yield
local status = coroutine.status
local floor = math.floor
local loop = {}
local function Pause()
print("Loop paused from internal coroutine")
loop.Running = false
return yield()
end
loop.Code = function(t)
print("Loop birth time: "..t.." seconds")
Pause()
print("Picking up")
wait(1)
end
function loop:Run()
local coro = self.Coro
if not self.Running then
self.Running = true
if not coro or coro and status(coro) ~= "suspended" then
coro = create(function()
local timestamp = tick()
while self.Running do
local elapsed = floor(tick() - timestamp)
if loop.Code(elapsed) == true then
print("Loop stopped from internal coroutine")
break
end
end
end)
self.Coro = coro
end
resume(coro)
end
end
function loop:Stop()
print("Loop stopped from external coroutine")
self.Running = false
end
loop:Run()
wait(5)
loop:Stop()
wait(5)
loop:Run()
Looks a bit complicated, as it should for a situation like this. This is probably the closest I could get to giving an example without making an entire task-scheduler. This basically just utilizes the yield function of the coroutine library, which exits the code block's running state, and can be used to queue it up to later be resumed. During this intermediate state, the program can spend time handling other tasks so no time is wasted.
2 comments
Have a variable set to true, and instead of while true do, use while VarName do. Then set the bool to false in the function?
^ Yeah, that works