Return is part of Lua’s global environment of keywords. The replies in this thread so far do a decent job of explaining it, but I’ll elaborate some more.
In Lua, break
and return
statements (as well as continue, which has been added to Luau but does not exist in vanilla Lua) allow you to jump out from a code-block.
Functions in Lua end with return by default, so if you do not need to receive any kind of value from your function, do not write a return statement. For Lua syntax, return can only exist as the last statement of a specific block. It would replace break statements in functions that actually need to see information provided (IE, if you need information, use return, if you only need to end code chunk, use break – this is why break is used in loops even though you could syntactically use return as well).
Here is a very basic example of return:
function GiveBack(Value)
return Value
end
print(GiveBack "Example") -- "Example"
Let’s ignore the fact that the above code is pointless. You’ve wrote a callable function GiveBack
. This function will implicitly return, because functions do that naturally. However, you want to get back the value that you pass to the function. So you write a return statement, and want your caller to receive it. In this case, the caller is our print statement.
What’s nice about Lua is how return acts in response to its syntax. You can return as much information as you’d like to.
Here’s another example. Pretend you were writing a function to decide what 25% and 75% of a passed number value were. Of course this function would only be useful if you could receive your result from it, and so you would need to return both values.
BaseNumber = 20
function GetPercents(Value)
return Value * .25, Value * .75
end
local Percent1, Percent2 = GetPercents(BaseNumber)
print("25% of BaseNumber is "..tostring(Percent1))
print("75% of BaseNumber is "..tostring(Percent2))
First we write a variable to represent some number we want to obtain the percentages of, followed by a function that calculates and returns those values. In Lua, you can catch and pass multiple values at once. We catch both results (because mathematical calculations are done inside the function we can assume results to always be number types) and assign them to variables. Then we can use those results at our higher scope, even though they were calculated in the function.