Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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 comment

1

Don't forget delay

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

This discussion is preserved as it was. New answers, comments, and votes are closed.