What does the return function do in studio?
Can stop a function, or stops and gives back a value after calling the function.
Example
function Test(a)
return a + 15
end
local Result = Test(5)
print(Result)
This will print 20 because a is 5 and
5+15 is 20
it returns a function Example:
local Part = Script.Parent
Part.Touched:Connect(function(hit) -- check if the object is touched.
if hit.Parent:FindFirstChild("Humanoid") then
else
return -- the function will basically stop or breaks the function or ends the function
end)
To be a bit more accurate. Return can end a function or send some data back to where it was called / sent first.
return is used inside functions. It will return a value and stop the function when called. If you don’t provide a value after “return” it will just stop the function and return nil.
local coinFlip = function()
local result = math.random()
if result == 0 then return "Tails" end
if result == 1 then return "Heads" end
end
print(coinFlip())
This code sample should print “Heads” or “Tails” in the output window.
The function return
defines the result of a function and/or stops the function. Leaving it undefined is equal to return nil
. Here’s an example in which I generate a part, then position it with a function:
function position(part)
newpart = part:Clone()
newpart.CFrame = CFrame.new(math.random(-200, 200), math.random(-200, 200), math.random(-200, 200))
return newpart
--part is the result as shown by return
end
local Part = Instance.new("Part")
local NewPart = position(Part)
print(NewPart.Name .. " was positioned!")
--expected outcome: "Part was positioned!"
Crazy, there’s already duplicates and you didn’t search!
Returning something will essentialy break a function and return something where you called the code.
An example of this:
local findPlayerFromDisplayName = function(display)
for i,v in pairs(game.Players:GetPlayers()) do
if v.DisplayName == display then
return v
end
end
end
print(findPlayerFromDisplayName('dylan')) -- returns player object or nil
Functions are very very useful, and essential to making good code and learning how to implement functions to make your code cleaner is vital in making good creations.
Didn’t see that post at all when I searched exactly “Return #help-and-feedback:scripting-support”
And other post didn’t seem that promising or relating to my question much.
So could you put this to get the returned function?
local v = findPlayerFromDisplayName()
Pretty much, whatever is returned from the function will be replied, in this case if you did not pass an argument; nothing would be replied, so the function would return ‘nil’.
local function turnstringintovariablestring(msg)
return msg
end
local message = turnstringintovariablestring("hi")
print(message) -- hi
local function turnstringintovariablestring(msg)
return false, true
end
local message = turnstringintovariablestring("hi")
print(message) -- false