Before you go, let me try.
Here’s a function that adds two numbers a
and b
. Pretend there’s code inside, and let’s assume both a
and b
will always be numbers (no strict typing needed here, although it’s good practice).
function add(a, b)
...
end
To call the function, we’d simply use add(a, b)
: for example, add(2, 5)
.
We want this function to add two numbers. Simple enough – let’s add the two numbers we pass into the function and store that value.
function add(a, b)
local result = a + b
end
Great. If we call add(2, 5)
, we’ll get 7. But how do we get this value out of the function?
That’s where the return
keyword comes in.
Let’s say we wanted to store that result
value outside of the function. To do this, we can use the return
keyword:
function add(a, b)
-- We add the two numbers
local result = a + b
-- We return the variable result, which is the sum of a and b
return result
end
Now, whenever add(a, b)
is called, we can use that result
value.
Now, we can assign a variable to add(a, b)
. We can do this because the return
value will give us back whatever result
is in that function.
local c = add(2, 5)
And as expected, c
will have a value of 7
.
local c = add(2, 5)
print(c)
-- 7
Returns are quite simple. Mess around with it in Studio and you’ll get a feel for it.