Understanding function "return"

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dumuz

I understand the return usage in being able to essentially stop running a function and calling other functions, changing variables, etc.

But from what I understand is that it’s also a manual override of returning a null to other functions that may have called it.

To me, this means that all functions are waiting for a response from whatever they’re calling to and the default is null. But if the return simply returned information. How could that be used?

for example:

func _callout():
	_grabbing_info()

func _grabbing info():
	var stuff
	#doing calculations
	if stuff > 10:
		return true
	else:
		return false

how could _callout() use/acknowledge/receive these returns?

Or am I completely wrong in my understanding?

:bust_in_silhouette: Reply From: nwgdusr999

you could just have var x = yourFunction(); and then use x however you want. Or use its result direct like in a if _grabbing_info() then do x else do y

But basically, in programming, you call a function to do something, or in some case, to run some code and obtain a result. If you just want to do some things and don’t need a result, you’d have a ‘void’ function; which returns nothing. If you need a result, you’d have a function which returns a value of a particular type, then you’d use ‘return’ to return the value. ‘return;’ is also used to ‘quit’ or exit from a void function in some languages, but that’s just a terminology thing, the main purpose of the return is to return a value.

Thank you guys for the response!

Dumuz | 2019-12-28 19:01

1 Like
:bust_in_silhouette: Reply From: johnygames

The thing with return is that it allows you to store a value, whatever this may be, in a variable. In your example you could simply write:

func _callout():
    info = _grabbing_info()

What that would do is store the output of the _grabbing_info() function in the info variable. In this case, info would be a boolean value equal to either true or false. You can then use this info variable as you wish.

Generally speaking, you use return when you want the function to output a value which you wish to use somewhere else. An alternative is to use a global variable (a variable accessible from all over your code) and upate it via your functions. For example:

var info = 0

func _callout():
    _grabbing_info()

func _grabbing_info():
    var stuff
    #doing calculations
    if stuff > 10:
        info = true
    else:
        info = false

If you don’t use the return keyword, then your function does not return any value. It just does some operations, but it does not output anything. Those functions are called void in other programming languages, exactly because they do not output any values. I hope this clarifies things a little.

Thanks for the clarification!

Dumuz | 2019-12-28 19:00