Environment Variables in GDScript

Our first example demonstrates how to work with environment variables in GDScript. Environment variables are a universal mechanism for conveying configuration information to programs.

extends SceneTree

func _init():
    # To set a key/value pair, use OS.set_environment
    # To get a value for a key, use OS.get_environment
    # This will return an empty string if the key isn't present in the environment
    OS.set_environment("FOO", "1")
    print("FOO:", OS.get_environment("FOO"))
    print("BAR:", OS.get_environment("BAR"))

    # Use OS.get_environment_keys to list all keys in the environment
    # Here we print all the keys
    print()
    for key in OS.get_environment_keys():
        print(key)

    quit()

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ godot -s environment_variables.gd
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

The list of keys in the environment will depend on your particular machine.

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 godot -s environment_variables.gd
FOO: 1
BAR: 2
...

In GDScript, we use the OS class to interact with environment variables. The set_environment method sets a variable, get_environment retrieves a variable’s value, and get_environment_keys returns a list of all environment variable keys.

Note that unlike some other languages, GDScript doesn’t provide a direct way to get all environment variables with their values in a single call. We need to iterate over the keys and fetch each value separately if we want to replicate that functionality.

Also, remember that when running a GDScript from the command line, we use the godot command with the -s flag to run it as a script.