Returning from a nested function, and also leaving the "parent" function.

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

Hi! How could I use “return” on a nested function and makes it to exit not only it self (the nested function), but also the “parent” function?

In the example below I want to return inside from the action_3 function if the condition is true, but I want to get out of the action_1 function too with one simple action.



func action_1 () -> void:
    action_2 ()
    action_3 ()
    print ("return just get out of or action_3")

func action_3 () -> void:
    if 2 + 2 == 4:
         #will return only from action_3 to action_1
:bust_in_silhouette: Reply From: drmrboyc

I don’t know GDScript well yet (just started looking at Godot a couple days ago), however in this case you might just want to return a boolean value from action_3() and exit action_1() early if action_3() returns true.

Assuming we’re going to do more than run a single line of code in action_3(), we’ll create a flag in action_3() that will be returned to the calling function, letting the caller decide what to do with the result.

func action_1() -> void:
    if action_3() == true:
        print("action_3() -> true. Bypassing action_4().")

func action_3() -> bool:        
    var ret_value: bool = false 
    if 2 + 2 == 4:
         ret_value = true
    return ret_value

edit: underscores were causing undesired italics in function names.