Answered by
7 years ago Edited 7 years ago
The Spawn
function creates a new thread for the thread scheduler to execute - it is for processing multiple actions at once. If you absolutely need to do two actions at once, what you're doing is fine.
The only alternative I may suggest is using the coroutine functions built into the API. Ultimately, these will produce the same outcome. But, coroutines are more powerful.
They allow you to be able to retrieve data outside of the initially defined thread(will give example)
You cannot yield the thread the spawn
function creates with the exception of internal yield functions (and wait
).
In other words, it is:
2 | print ( "hold on mydude, gotta go get something" ) |
4 | local externalData = "Bob" ; |
7 | print ( "alright i'm back, the guy's name was: " ..externalData") |
vs:
01 | local a = coroutine.create( function () |
02 | print ( "hold on mydude, gotta go get something" ); |
03 | local externalData = coroutine.yield(); |
04 | print ( "alright i'm back, the guy's name was: " ..externalData); |
07 | local theInfoInTheOtherRoom = "Bob" ; |
11 | coroutine.resume(a,theInfoInTheOtherRoom); |
See what I mean? It's one thread, rather than two threads.
Note that I know this situation doesn't seem relevant to yours, and that I am mainly providing an example as to why you might consider using coroutine functions rather than spawn
The coroutine.yield
function will stop the thread until coroutine.resume
is called upon the thread, externally, and will return whatever arguments were passed with resume
So, the coroutine equivalents to your code would be:
1 | local count = coroutine.create( function () |
4 | pl.Range = pl.Range * ( 1 - counter / 10 ) |
9 | coroutine.resume(count); |
1 | local count = coroutine.wrap( function () |
4 | pl.Range = pl.Range * ( 1 - counter / 10 ) |