Hi guys, I’ve been having trouble on understanding on what the return keyword what it does and how to use it. I would like to know on how to use and what it does
I need 3 examples and thank you for taking your time on reading this
Hi guys, I’ve been having trouble on understanding on what the return keyword what it does and how to use it. I would like to know on how to use and what it does
I need 3 examples and thank you for taking your time on reading this
function add_one(number)
return number + 1
end
print(add_one(1)) -- 2
Returns can be quite useful! They allow you to return info, and stop code in its tracks! So here are some examples
-- returning data
local function getData()
local data = {}
return data
end
local data = getData() -- this will give us the data table we created in the getData function, we can return just about everything, from ints, to strings, to heck, the entire workspace!
-- we can also use it to check if theres a certain value, if not we stop the function from running
local function getCheeseLevel()
if not player.HasCheese then return end -- we use return so the code after this point wont run, but this is only triggered if the player doesnt have cheese or whatever lol
return player.CheeseLevel -- this will run if the if statement above doesnt have its requirement's met, hence not returning, meaning this code will run
end
-- now say we did this in a script
local bean = false
return
print(bean)
-- this wouldnt work as the return stops any code from being triggered after it, except for the case of a function, where if you trigger a return in it, it will stop code in the function, and not the entire script as a whole, but when using it straight up in the script, well it stops all code. Im sure theres a better word for this but I cant think of it.
-- more to note:
return -- if we just use return by itself it will return nil, or nothing. But if we give it a value to return it will pass said value, as shown with my examples above.
If you have any more questions feel free to ask! I know return was a little complicated when I started so I’d be glad to help you out!
tysm, I understood this very well. I will never forget you
Thanks! Just trying to help everyone out around here! :D
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.