Exit in GDScript
Here’s an idiomatic GDScript example demonstrating the concept of exiting a program:
This GDScript example demonstrates how to exit a program prematurely using the quit()
function. Here’s a breakdown of the code:
We extend
SceneTree
to create a script that can be run directly from the command line.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.
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:
- Save the code in a file named
exit_example.gd
. - Open a terminal and run the script using Godot’s command-line interface:
To check the exit status:
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.