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()
	local p,data = INPUT_EVENTS.CheckFeint.OnServerEvent:Wait()
	print("client check")
	return data

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)
	if feint.Value or res then

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.

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
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.


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.

--Code here is executed without being disrupted.

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.