Answered by
8 years ago Edited 7 years ago
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:
06 | print ( "Loop is running" ) |
09 | print ( "Stopped running" ) |
13 | local function 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.
03 | local create = coroutine.create |
04 | local resume = coroutine.resume |
05 | local yield = coroutine.yield |
06 | local status = coroutine.status |
07 | local floor = math.floor |
14 | print ( "Loop paused from internal coroutine" ) |
20 | loop.Code = function (t) |
21 | print ( "Loop birth time: " ..t.. " seconds" ) |
28 | local coro = self.Coro |
30 | if not self.Running then |
33 | if not coro or coro and status(coro) ~ = "suspended" then |
34 | coro = create( function () |
35 | local timestamp = tick() |
38 | local elapsed = floor(tick() - timestamp) |
40 | if loop.Code(elapsed) = = true then |
41 | print ( "Loop stopped from internal coroutine" ) |
54 | print ( "Loop stopped from external coroutine" ) |
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.