To return
is to just get a value back from a function. Take this example into consideration:
local function add(num1, num2)
return num1 + num2
end
-- You could also write the function like this:
local function add(num1, num2)
local sum = num1 + num2
return sum
end
-- The functionality would be the same, the top one is just more efficient
If you know how parameters work, you’d know you can plug in whatever (number) you want for num1
and num2
. So, for example, you could do this:
local sum = add(10, 25)
print(sum) -- prints 35, because 10 + 25 is 35
You can obviously make more complex functions that will make returning a single value more useful. A more useful (and simple) function that returns a value could be finding the distance between two parts.
If you’re into math, specifically vectors, you’d understand why this code works. But for now, let’s just assume you know why it works. Here’s how it’d look:
local function disanceBetween(part1, part2)
return (part1.Position - part2.Position).Magnitude
end
With this function, you could check the distance between your player (via your character’s HumanoidRootPart) and any part in workspace. This could be useful if you wanted to allow players to press E to open a door for example. Constantly check if your player is in range of the door by using this function in conjunction with a Heartbeat loop.
This example below would just make the part named “GlowPart” in workspace Neon if you were within 10 studs of it’s radius.
local runService = game:GetService("RunService")
local glowPart = workspace:WaitForChild("GlowPart") -- pretend this exists
-- use your imagination here and also pretend I've already defined the local player, character, and HRP (HumanoidRootPart)
-- (I didn't for simplicity reasons, this is a lesson about *returning*
runService.Heartbeat:Connect(function()
-- you could either store it in a variable like so:
local distance = distanceBetween(HRP, glowPart)
if distance <= 10 then
glowPart.Material = Enum.Material.Neon
elseif distance > 10 and glowPart.Material ~= Enum.Material.SmoothPlastic then
glowPart.Material = Enum.Material.SmoothPlastic
end
-- Or you could just directly check it like this:
if distanceBetween(HRP, glowPart) <= 10 then
-- same functionality as above
end
end