Exit in GDScript

Here’s an idiomatic GDScript example demonstrating the concept of exiting a program:

extends SceneTree

func _init():
    # This print statement will be executed
    print("Starting the program")
    
    # This deferred function will not be called when using quit()
    call_deferred("_deferred_print")
    
    # Exit the program with status code 3
    quit(3)

func _deferred_print():
    print("This will not be printed")

# Run this script from the command line:
# godot --script exit_example.gd

This GDScript example demonstrates how to exit a program prematurely using the quit() function. Here’s a breakdown of the code:

  1. We extend SceneTree to create a script that can be run directly from the command line.

  2. In the _init() function (which is called when the script is run):

    • We print a message to show that the program has started.
    • We schedule a deferred function call using call_deferred().
    • We call quit(3) to exit the program with a status code of 3.
  3. The _deferred_print() function is defined but will never be called because we exit the program before it has a chance to run.

To run this script:

  1. Save the code in a file named exit_example.gd.
  2. Open a terminal and run the script using Godot’s command-line interface:
$ godot --script exit_example.gd
Starting the program

To check the exit status:

$ echo $?
3

Note that the “This will not be printed” message never appears because the program exits before the deferred function is called.

In GDScript, quit() is similar to os.Exit() in Go. It immediately terminates the program with the given status code. Any deferred or scheduled functions will not be executed after quit() is called.

Unlike Go, GDScript doesn’t have a built-in way to capture the exit status when running a script normally through the Godot editor. However, when running the script from the command line as shown above, you can check the exit status using shell commands.

This example demonstrates how to exit a program prematurely and with a specific status code in GDScript, which can be useful for error handling or controlling program flow in more complex applications.