Basically I don’t know how to make it useful, and I’ve seen some people saying that it is used to stop functions
return is used to stop functions, yes, but it is also used to return certain things, for example a string.
local function returnString()
return "This is a string"
end
print(returnString())
You can also use return
to exit a for
loop. It’s also used to un-nest your code.
for
loop ex:
local Table = {"One", "Two", "Three", "Four"}
for _, number in Table do
if number == "Two" then
return
end
print(number)
end
--Output:
--One
Un-nest example:
-- Nested code:
function printIfNumber(valueToPrint)
if typeof(valueToPrint) == "number" then
print(valueToPrint)
end
end
-- Un-nested code using `return`:
function printIfNumber(valueToPrint)
if typeof(valueToPrint) ~= "number" then
return
end
print(valueToPrint)
end
Returning
is typically used to send info from 1 function
to another… a very simple (although unnecessary) way of Returning
would be to make a set of functions
, 1 generates 2 Random numbers and Returns
them, the other function
recieves the Return
and adds them together.
Here is what the code would look like:
function generateRandomNumbers()
local number1 = math.random(1, 50)
local number2 = math.random(1, 50)
print("Random Numbers: " .. number1 .. ", " .. number2)
return number1, number2 -- we parse the 2 random number variables out to whatever function / part of the code wants to receive it
end
function addNumbers()
local number1, number2 = generateRandomNumbers()
warn("Recieved numbers from the 'generateRandomNumbers' function!")
print(number1 + number2)
end
addNumbers()
U can use return to callback info from a function, for example if i have a function like this:
‘local function pow(a, b) return a^b end print(pow(5, 2))
This function will return the result of a^b so it will print 25
(Typed this on phone so it is ban but works)
If you run a loop and return it breaks the loop like break
Thank you, I think I understand it way better
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.