Question about return keyword

Godot 4.3

Am I using the return keyword correctly? Some functions I use it and not in others and I’m not sure when it is necessary. Can code execution get stuck in a function without a return exit? As an example, please consider the following code that I wrote for a light switch in my game:

extends InteractiveItem

# base script for all light switches

@export var target_light: Node # the light the switch controls
@export var probe: ReflectionProbe # a nearby reflection probe to update
@export var switch_on: bool = true # start on unless noted otherwise

var busy: bool = false # prevent spam actions

@onready var animation: AnimationPlayer = $AnimationPlayer
@onready var sound: AudioStreamPlayer3D = $AudioStreamPlayer3D

func _ready() -> void:
	animation.animation_finished.connect(_on_animation_finished)
	
	if not switch_on: # if the switch was set to off,
		animation.play("light_switchAction") # ensure switch is set to off
	
	if target_light: # if not null, 
		target_light.light_on = switch_on # command the light state to the switch state

func action() -> void:
	if busy: # prevent spam clicking
		return
		
	busy = true # mark as busy until animation finishes
		
	if switch_on: # if on,
		animation.play("light_switchAction") # turn to off
		activate_target_light()
		reflection_probe_update()
	else: # if off,
		animation.play_backwards("light_switchAction") # turn to on
		activate_target_light()
		reflection_probe_update()
		
	if not sound.playing:
		sound.play() # play sound if not already playing
	
	switch_on = not switch_on # toggle the switch
	
func _on_animation_finished(anim_name: StringName) -> void:
	if anim_name == "light_switchAction":
		busy = false # allow the switch to be used again
		
func activate_target_light() -> void:
	if target_light: # make sure it's not null
		target_light.action() # activate target light
	else:
		return
		
func reflection_probe_update() -> void:
	if probe: # make sure it's not null
		probe.update_mode = ReflectionProbe.UPDATE_ONCE # trigger probe update
	else:
		return
	
	
	
	

1 Like

For functions that do not return a value (in other words, void), you do not need a return as the final line. You will need a return if you want to return prior to getting to the end of the func.

In your action() func, the if busy: return statement is needed since there is a condition where you do not want to perform statements.

For the reflection_probe_update() functions, the else return is not needed.

For functions that do return a value, there must a return path for all cases.

4 Likes

That’s very helpful. Thank you!

2 Likes