I was watching someone code and i saw them do
function get() for _,v in pairs(game.Players:GetPlayers()) do if v.Name == title.Text then return(_) end end end
This is for a spectating script and later on they do
local num = get()
and they add +1 to num. I dont understand how that function even returns a number value?
Note: This answer assumes (kinda) that you have knowledge on for loops, functions, tuples, etc. If not, links/explanations are supplied at the end of the answer.
Return
is a function that, well, returns a value (or values) when prompted to. In the case of your script, it returns an index
(I like to call it an iteration
/iterator
, as you'll see later on). The return
function can be used for different purposes, such as returning a value in a table:
local exampletable = {'Hello', 'World'} function GetValue(tbl, val) for i, v in next, tbl do if v == val then return i, v end end return nil, nil --< Returns nothing if there was no match; a "fail-safe" end local i, v = GetValue(exampletable, 'World') print(i, v)--> 2 World
As you'll see (or noticed XP) it'll return what the current iteration in the table was, and what value it was on when it found the match. To note, you don't always need to use return
like that; you can even use it for CONFUSING MATH!!! >>:O
function Add(...) --> `...` is a tuple local numbahs = {...} local num = 0 for i, v in next, numbahs do num = num + v end return num end print(Add(5, 7, 1, 3), 'was the final result') --> 16 was the final result
And as you'll see (again XP) it returned all the numbers added up! :D
I'm tired, so I'm gonna leave here. Bai...
GET BACK HERE! FINISH IT!
Alright. ;-;
There's so many possibilities you can use return
for, and there's many advantages to using it! Don't be afraid to use it, or anything else you may discover! You might be surprised in what you might find. :)
NOW, ONTO THE ST00F!!!! >>:OOOOOOOOO
St00f touched on, yet barely explained by this fr00b
Tuples
- The ability to use as many arguments in a function as much as you want! :D The catch: You gotta account for each and every one, and (don't quote me on this) put it in a table. qq
Generic Fors
- A for loop
that returns both the iteration and value in a table. Only catch is that you need to give it a table. (Please don't quote me on that qq)
Return
- Returns values given to it.
Tyvm for reading! ^^ I hope this helped!
Hi PoePoeCannon,
Thanks,
Best regards,
~~ KingLoneCat