Environment Variables in AngelScript

Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables.

void main()
{
    // To set a key/value pair, use setEnvironmentVariable
    // To get a value for a key, use getEnvironmentVariable
    // This will return an empty string if the key isn't present in the environment
    setEnvironmentVariable("FOO", "1");
    print("FOO: " + getEnvironmentVariable("FOO"));
    print("BAR: " + getEnvironmentVariable("BAR"));

    // Use getEnvironmentVariables to list all key/value pairs in the environment
    // This returns an array of strings in the form "KEY=value"
    // You can split them to get the key and value
    // Here we print all the keys
    print("");
    array<string> envVars = getEnvironmentVariables();
    for (uint i = 0; i < envVars.length(); i++)
    {
        array<string> pair = envVars[i].split("=");
        print(pair[0]);
    }
}

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

FOO: 1
BAR: 

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

TERM_PROGRAM
PATH
SHELL
...
FOO

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

$ BAR=2 scriptname.as
FOO: 1
BAR: 2
...

Note: AngelScript doesn’t have built-in functions for environment variables, so this example assumes the existence of custom functions setEnvironmentVariable, getEnvironmentVariable, and getEnvironmentVariables. In a real AngelScript environment, you would need to implement these functions using the host application’s API or some other method to interact with the system’s environment variables.