How do I create a task.spawn function?

Hello, recently I have been doing something that requires a loop and has a timeout, and the problem is that with the timeout, it interrupts the rest of the script

So I want to do it in the background, but I don’t know how to do it


local SpawnTree = task.spawn(function(ExpectGrowth, Point, Propertys)
	task.wait(1)
end)

function Trees:Start()
	self.Enabled = true;
	local Spawns = {}
	for i, SpawnModel in pairs(TreesFolder:GetDescendants()) do
		if(SpawnModel.Name == "TreeAssets")then
			table.insert(Spawns, SpawnModel)
		end
	end
	
	local SelectedSpawns = self:RandomNums(Spawns, math.round(#Spawns/math.random(2, 3)));
	
	for i, obj in pairs(SelectedSpawns)do
		SpawnTree(math.random(0, 0), obj,obj.Parent:GetAttributes());
	end
end

Technically:

local SpawnTree = task.spawn(function(ExpectGrowth, Point, Propertys)
	task.wait(1)
end)

function Trees:Start()
    task.spawn(function()
	    self.Enabled = true;
	    local Spawns = {}
	    for i, SpawnModel in pairs(TreesFolder:GetDescendants()) do
		    if(SpawnModel.Name == "TreeAssets")then
			    table.insert(Spawns, SpawnModel)
		    end
	    end
	
	    local SelectedSpawns = self:RandomNums(Spawns, math.round(#Spawns/math.random(2, 3)));
	
	    for i, obj in pairs(SelectedSpawns)do
		    SpawnTree(math.random(0, 0), obj,obj.Parent:GetAttributes());
	    end
    end)
end
1 Like

SpawnTree will be nil? task.spawn is not like coroutine.wrap.

You’d use coroutines since they start in a suspended state, tasks are executed immediately.

2 Likes

task.spawn returns a thread value.

I was using the old documentation site, did the return value change? Here it says that it returns nothing. I’d also expect the thread to die after 1 second. And we can’t call a thread as far as I know, or use the operator (if that even is an operator, I don’t think it was on Lua).

To clarify, I was talking about calling, it’s not actually an operation but a type of expression as I’ve just learned here from the Lua 5.4 manual. What I meant was that this will error: coroutine.create(function() --[[statements]] end)() (on runtime)

The return value is a thread (according to the new docs).

spawn(functionOrThread: function | thread, ...: Variant): thread

Have no idea, but either way, I didn’t mean to include that in there.

I’d also expect the thread to die after 1 second.

Correct, in this example the thread would have a ‘dead’ state after one second.

And we can’t call a thread as far as I know

Threads can be resumed/yielded/closed (not called/invoked) etc.

or use the operator

I’m not sure what you’re referring to.

So I think I better put a task.spawn() to the SpawnTree function

() is technically not an operator, it’s just the syntax for calling functions/methods.

1 Like