Hey! I’m wondering what return
does in roblox lua scripting. Any help would be greatly appreciated! Thanks!
In a ordinary normal script function, it does what the keyword does.
for example
local a = 2
local b = 4
local function Sum(num0, num1)
return num0 + num1 -- Returns the sum of the 2 numbers
end
print(Sum(a, b)) -- 6
Is there any good use cases for return?
There exists a version of return where its on a module script, if you know about it, it is like a package that you can call require() on it and access the functions you have built inside it
If you want to exit a function if a condition exists you can place a return in an if then statement: i.e. “if not variableX then return end” I use that often, helps avoid errors in functions like if an object no longer exists after a delay
In all (most) languages, there is a return keyword. This is used in various different ways, but will return the specified value from the function scope. IE:
Say we want a function that ‘returns’ the distance between two humanoids:
local function getDistance(humanoid1, humanoid2)
local humanoid1rootpart = humanoid1.Parent.PrimaryPart
local humanoid2rootpart = humanoid2.Parent.PrimaryPart
return (humanoid1rootpart.Position - humanoid2rootpart.Position).magnitude
end
Now, we can call this function with the provided arguments and it will give us the distance between the two humanoids.
local h1 = someHumanoid
local h2 = someHumanoid2
local distance = getDistance(h1, h2)
if distance > 10 then
print("Distance is too large")
else
print("Distance is close enough")
end
Here are few more small module methods showcasing the use of returns for my game I am working on:
--Gets a random point near a point, within radius
function module.getRandomPointNearPoint(v3d, radius)
radius = radius * 10
local rp = Vector3.new(
module.random(radius *-1, radius),
0,
module.random(radius*-1,radius))
rp = rp + v3d
return rp
end
--Gets a random vector between two vectors
function module.randomVectorBetween(v3d1, v3d2)
local x = module.random(v3d1.X,v3d2.X)
local y = module.random(v3d1.Y, v3d2.Y)
local z = module.random(v3d1.Z, v3d2.Z)
return Vector3.new(x,y,z)
end
--Gets the Players->Player by name.
--If you need the serverside client,
--use .getWorkspaceClient method
function module.playerByName(name)
local playerGroup = game.Players:GetPlayers();
for i,pl in pairs(playerGroup) do
if(string.lower(pl.Name) == string.lower(name)) then
return pl
end
end
return false
end
return can be used to return a value back to a function to make that function become the value that you return to the function it also can be used to break a function
function add(a, b)
return a + b
end
local sum = add(5, 3) -- sum will be 8
print(sum) -- Output: 8
function processNumber(num)
if num < 0 then
print("Negative numbers are not allowed.")
return -- Exits the function immediately
end
end