So I've only used return for on thing and that's to return end. Ex,
if not player then return end
But I really don't know anything else. Let's say I do something like this,
local x = 5 function oddOrEven(x) if x%2 == 0 then return false else return true end end oddOrEven(x)
How would you get if its true or false. And yes this might be unnecessary in the example but because of my lack of knowledge on returns I don't really know what they would be used for. If someone could tell me how return works and what it's used for I would be really happy (:
Also, I'm okay at roblox scripting I just haven't gotten around to how return works.
When using return:
When return is used in a function, the function stops executing. The function now holds the values returned. * Notice that *return does not execute in a Module Script.
Examine this code to understand this idea better: Holding a String Value:
function GetRandomString() local texts = {"Hello, I'm R15E", "Welcome to Whatever", "Hello World"} -- Some random text local randomize = math.random(1,#texts) -- Get a random text local picked = texts[randomize] -- Get the string return picked -- Code would not work after this is stated, if there is, it would error. end function PrintRandom() local RandomText = GetRandomString() -- The string value would be returned to this value. print(RandomText) -- Now we print the value. end PrintRandom()
Another Example Holding a Boolean Value:
local Enabled = true function Check() -- Checks if the value is true if Enabled then return true -- this obviously returns "true" else return false -- this obviously returns "false" end end if Check() then -- In this case, it returns true, the rest of the code is executed. game.Workspace.Music:Play() -- Just something random happens if it returns true. end
Obviously the above code wouldn't need to execute the code as you can just check if the value is true or false. But, it's just an example.
return
puts whatever is returned where the function is called. For example:
local function addNum(x, y) return x+y; end print(addNum(2, 2)); --in this case prints 4 -- putting return in the function makes the function call act like this: print(2+2);
You could also use return for logic comparisons.
local function minPlayersReached() if game.Players.NumPlayers >= 2 then return true; else return false; end end if gameStarted and minPlayersReached() then --assuming gameStarted is some defined variable callNextFunction(); end
Additionally, return exits a function.