What does return do aside from breaking functions?

Hello!

I feel kind of stupid asking this considering I’ve done some other research online and it came up as a “basic” part of Lua, but I just haven’t been able to understand it, or any articles on Lua.org.

I know return can break a function, and return to another function if that’s what’s calling it, however sometimes I see people returning arguments, like return a or b and I don’t know what it means or what it does.

You can send back a variable from the function. It’s useful if you have a function that does some form of math or combines multiple strings:

local function addNumbers(num1, num2)
	local result = num1 + num2
	return result
end

print(addNumbers(1,3)) --This prints 4

Instead of…

local function addNumbers(num1, num2)
	local result = num1 + num2
	print(result)
end

addNumbers(1,3)

Roblox Developer Hub Page (For more in-depth to what return can do)

3 Likes

Oh, okay, thanks! I’ve seen some rounding functions that use return, and just haven’t been able to grasp it. Does it put a yield or anything, such as if you’re using a RemoteEvent and are waiting for a return from the secondary script, if that makes sense?

Are you talking about using a Module Script or like a BindeableFunction? Since a normal function will only run in the script it’s in.

For getting a response from the server, I would suggest using RemoteFunctions. But if you are communicating between scripts, just use BindableFunctions or BindableEvents.

1 Like

I mixed up Bindable and Remote functions, oops.
I’ll make an example here, excuse the lack of indentation, not sure why I can’t put them on here:

Script 1:

function FireEvent()
local variable = 1
PretendThisIsAnEvent:Fire(variable)
print(variable)
end

Script 2:

PretendThisIsAnEvent.Event:Connect(function(variable)
variable = 5
wait(5)
print("ok waited")
return variable -- would the first script wait for the 5 seconds for this return, and then 5 be printed from the first script?
end

RemoteEvents wouldn’t wait since they just fire and don’t except a result but a RemoteFunction would yield since it is expecting a result to return.

1 Like

I feel so stupid, I kind of forgot about them until Quwanterz’ reply. Didn’t know RemoteFunctions would have a yield though, thanks! I guess I thought RemoteFunctions and Events were the same thing haha.

Yup, that’s why you never want to use a RemoteFunction from Server > Client > Server since exploiters can modify their local script to never return a result and yield your server script.

1 Like

Good to know, will definitely keep that in mind as I am actually using that in my game for coins. Seems easily exploitable, good thing it isn’t released yet.

Thanks again for the help! I appreciate it.

1 Like