function say(text)
task.wait(5)
print(text)
end
say("Hello")
How do I pause the function suddenly without having to wait for it to finish? I have tried coroutines but I don’t quite get how they work in this case. Help would be appreciated
function say(text)
task.wait(5)
print(text)
end
say("Hello")
How do I pause the function suddenly without having to wait for it to finish? I have tried coroutines but I don’t quite get how they work in this case. Help would be appreciated
Coroutines should work.
An alternative is task.spawn and task.cancel which you should look into.
add return
to the end of the function
for example:
function example()
wait(1)
local randomNumber = math.random(1,4)
if randomNumber == 1 then
return randomNumber.." yay 1"
end
-- if will number 1, script will return randomNumber.." ok" and stops
return randomNumber.." no 1"
end
local gotNumber = example()
print(gotNumber)
if it’s wrong answer then ping me I will answer, I didn’t understand the question
Based on the answer with coroutines above, you would want to wrap your function using the task library and then cancel it. You can then pass the arguments to the function by simply including them in task.spawn
.
local thread = task.spawn(say, "hello")
task.cancel(thread)
coroutine.close
would work too for task.cancel
, but it returns info about the thread’s state that we do not want in this case.
It seems to only cancel the thread after the thread has finished
It shouldn’t, so I assume you may have put the code inside the function or something else is happening.
The function should never print in this case:
local function say(text)
task.wait(1)
print(text)
end
local thread = task.spawn(say, "hello")
task.cancel(thread)