How to set a spawn() function as a connection

I’m having trouble setting a spawn() function as a connection.

My code:

local connection

connection = spawn(function()
end)

-- this will print the connection is nil
local part = script.Parent

local function connection()
	return task.spawn(function()
		print("Hello.")
	end)
end

part.Touched:Connect(connection)
1 Like

The .Touched event was just an example, the same logic applies.

local part = script.Parent

local function connection()
	return task.spawn(function()
		print("Hello.")
	end)
end

local conn = part.Touched:Connect(connection)
task.wait(5)
conn:Disconnect()

What script are you currently working with? You don’t have to provide the full thing.

local condition = true

task.spawn(function()
	if condition then
		--do code
	end
end)

You can only disconnect callback functions connected to events through the use of the :Connect() method.

You could use a while loop to run while the condition is true, since they run infinitely rather than if statements which run once.

Example:

local currentString = "Hello"
local TargetString = "Hello"

local StopCondition = false -- this is an example, setting to true would stop the loop

task.defer(function() -- this is the same as spawn() (you could also use task.spawn)
	while (currentString == TargetString) and not (StopCondition) do
		-- Run something
	end
end)

Once the function body of task.spawn() completes the created thread is ended.

1 Like

In simpler terms to what @Forummer said, yes. Once the function ends, it should clear it from memory.

1 Like