I have these two loops, but it seems like the second one waits until the first one is done to run :(
Please help!!
local val1 = script.Parent.Parent.Value local val2 = script.Parent.Parent.Value1; function reduce1(value) while wait(12) and value.Value > 1 do value.Value = value.Value -1; end; end; function reduce2(value) while wait(6) and value.Value > 1 do value.Value = value.Value -2; end; end; reduce1(val1); reduce2(val2); --This runs after the above one..
Notice how both functions have waits in them? Because of this, then the script will wait for the first function before it reads the rest of the code(the next function). Due to this - you need to use couroutines
!
Coroutines are separate threads
. To understand what a thread is think of it like this - the script is a thread. What a coroutine does is it creates a new thread, that runs at the same time as the script.. thus eradicating any yields betwixt the two. In basic terms - wait()
's are ignored for the rest of the script.
There are two ways that are normally gone about this.
1) Using the coroutine.wrap
function
The coroutine.wrap function takes in a function as the argument(the code that you wish to make a coroutine) and returns a callable thread.
--Call the coroutine.wrap function, with arguments of a function coroutine.wrap(function() wait(10) print('Hi') end)() --Call the returned thread. print('Bye')
The above code would print 'Bye', wait 10 seconds, then print 'Hi'. Whilst normally, because of the wait in the code.. it would wait 10 seconds, then print 'Hi' and 'Bye' consecutively.
2) Using coroutine.create
and coroutine.resume
.
The coroutine.create function takes in the arguments of a function, and returns a thread. The coroutine.resume function is needed to run this thread!
coroutine.resume(coroutine.create(function() wait(10) print('Hi') end)) print('Bye')
The same results as example 1 would happen.
You need to wrap your first function in a coroutine, eliminating the waits so that your second function can run!
local val1 = script.Parent.Parent.Value local val2 = script.Parent.Parent.Value1; function reduce1(value) while wait(12) and value.Value > 1 do value.Value = value.Value -1; end; end; function reduce2(value) while wait(6) and value.Value > 1 do value.Value = value.Value -2; end; end; coroutine.wrap(reduce1)(val1); --Wrap the function then call it! reduce2(val2);