Task.spawn() and Returning Values

Hello everyone,

I have a script that needs to check the client for a boolean value within a set time limit.

Right now what the script does is it spawns a thread using task.spawn() to ping the client for the boolean.

This is the code for that function:

local function checkFeint()
	INPUT_EVENTS.CheckFeint:FireClient(player)
	local p,data = INPUT_EVENTS.CheckFeint.OnServerEvent:Wait()
	print("client check")
	print(data)
	return data
end

it then checks immediately after firing to see if the boolean is true with a fallback value on the server incase that ping wasn’t fast enough. This is done with the following code:

        if SETTINGS.FastFeintsEnabled.Value then
		res =  task.spawn(checkFeint)
	end
	if feint.Value or res then
		print(res)
		return 
	end

Unfortunately, the variable res will always be set to a thread object, meaning res doesn’t get change from the logic in the checkFeint() function.

TL;DR
How do I return values from a function that is called through task.spawn()?

You can use coroutine.create to do this:

local thread = coroutine.create(function()
    return 500
end)
local successful, result = coroutine.resume(thread) -- note the first value returned from coroutine.resume is always a bool dictating whether resuming the thread was successful
print(result) --> 500
1 Like

task.spawn() can’t return values, its documentation states as such.

https://developer.roblox.com/en-us/api-reference/lua-docs/task

You could use non-locals (upvalues) to achieve this or coroutines (if your implementation allows for it). I’m not sure why you’re using task.spawn() though, you could use task.delay() to wait for some specific length of time before checking the Boolean variable without disrupting the main thread of execution, i.e;

task.delay(3, function() --After 3 seconds the function is executed.
	if condition then --Check condition.
		--Do code.
	end
end)

--Code here is executed without being disrupted.
2 Likes

You shouldn’t be wanting data returned if you’re running it in a separate thread.
You’re doing stuff regarding remotes, those will always take some time.

I recommend handling the data inside of the thread itself or don’t use it at all.