Hey. I'm looking for a good example of returning. I know how to return but it seems useless to me, thanks.
Returning a value is basically the opposite of passing arguments to a function. It allows the function to give back data to whatever called it. Take this addition script, for instance:
local function doAddition(addend1, addend2) local sum = addend1 + addend2 -- add the values end
As you can see, the above is a perfectly functioning addition method. However, it is of little use if there's no way to get back the sum. That's what returning is for:
local function doAddition(addend1, addend2) local sum = addend1 + addend2 -- add the values return sum end
Perfect. The last thing that needs to be done is to provide a container to store the returned sum:
local function doAddition(addend1, addend2) local sum = addend1 + addend2 -- add the values return sum end local someInteger = doAddition(5, 5) print(someInteger)
First, the above script defines the doAddition()
function. Then, the variable someInteger
is created, and it calls doAddition()
, passing 5 and 5 as arguments. Within the function, the local variable sum
is defined and is set to equal to addends one and two. Then, it passes back the value of sum
. At this point, 10 should appear in your output.