Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Loop won't continue untill function is over?

Asked by
Mokiros 135
9 years ago

I have "while true do" loop which calls a function every 0.1 seconds

while true do
    wait(0.1)
    func() --function
end

And function have 1 second delay:

function func()
    wait(1)
    print("Done")
end

The problem is - loop won't continue untill function will be over, and that means function will run every 1 second instead of 0.1. How do i fix it?

2 answers

Log in to vote
2
Answered by
M39a9am3R 3210 Moderation Voter Community Moderator
9 years ago

In order to have your 'func' function fire every .1 seconds, you will want to use the spawn function. spawn() is much like coroutine.wrap(function() end)(), which is the equivalent to coroutine.resume(coroutine.create(function() end)) except you can do a few more things with coroutines. Spawn and Coroutines are kind of like threads someone can probably explain this better than I can, to put it in simple terms, it is like your function is running in another script.

Since you already defined your function you do not need to copy and paste the function into the spawn function.

function func()
    wait(1)
    print("Done")
end

while true do
    wait(0.1)
    spawn(func) --Now if you did want to copy and paste the code from above into here, it would be like below
    --spawn(function()
    --wait(1)
    --print("Done")
    --end)
end
Have any questions, feel free to ask! If this answer helped or solved your problem then don't forget to leave an upvote and accept the answer.
Ad
Log in to vote
0
Answered by 9 years ago

Coroutines, what are you trying to make? I would make the function into a coroutine because scripts read like a book and when you call a function the function is read same. Coroutine's are the only way to run a function multiple times in a same sccript

Answer this question