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

is there any way to run a function in the background?

Asked by 5 years ago

hi there, I am making a script and i need a script to call a function but not wait for it to end. any ideas?

2 answers

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

There are several things you can use to make different threads inside the same script.

First there is the spawn function

spawn(function()
    --//Any code you put in here won't yield the rest of the script below it
    wait(10)
end)

print("I still print before 10 seconds!)

Spawn documentation

Coroutines are another choice. These do basically the same thing however they have more features than spawn.

Here's an example

local function Play()
    --//Will not yield the rest of the script
    wait(10)
end

local Thread = coroutine.create(Play)
coroutine.resume(Thread)

They will probably get harder to get used to, but it's worth it.

Coroutine documentation

That basically sums it up, hope this helps.

1
Don't forget delay BlackOrange3343 2676 — 5y
Ad
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

Simple answer: Wrap the function in a coroutine:

print("1")
coroutine.resume(coroutine.create(function()
    while wait() do
        Instance.new("Part",workspace)
    end
end))
print("2")
-- Console output:

--> 1
--> 2

Answer this question