Does this return statement return to the RemoteFunction or the Anonymous function?

I was writing this return statement, and want to make sure that it will return to the remote function. To solve this, I have a variable called toReturn and the code works through that, but I was wondering if the same could be achieved without “toReturn”.

Response is defined in a later line.

it returns to the anonymous function. And by the time your spawned function finished your remote function is allready done and returned nothing

example test this out
Server

local rFunc = Instance.new("RemoteFunction")
rFunc.Name = "TestRemoteFunction"

rFunc.OnServerInvoke = function()
      print("Start")

      task.spawn(function()
            task.wait(5)
            print("Send response")
            return "Hello World"
      end)

      print("End")
      return "Nil Response"
end

rFunc.Parent = game:GetService("ReplicatedStorage")

Client

local rFunc = game:GetService("ReplicatedStorage"):WaitForChild("TestRemoteFunction")
local result = rFunc:InvokeServer()
print(result)

output:
Server → Start
Server → End
Client → Nil Response
after 5 seconds
Server → Send response

The spawn function create a spererate thread that doens’t yield upper function

A better way to achieve what you want is probably with RemoteEvents instead

A ‘return’ statement will just return out of the immediate function.

local function f()
	local function f2()
		return --Doesn't return out of the call to 'f'.
	end
	
	f2()
	print("Hello world!") --This is output.
end
f()

It should be noted that task.spawn only returns a single thread value, it will not return any of the values returned in its function body.

1 Like

The thing is, I’m invoking a client. That mean’s there’s a chance they don’t respond which is why I want to make sure I have a timeout on the response.