Lua by Example: Environment Variables

Environment variables are a universal mechanism for conveying configuration information to Unix programs.

To get a value for a key, use os.getenv. This will return nil if the key isn’t present in the environment.

print("FOO:", os.getenv("FOO"))
print("BAR:", os.getenv("BAR"))

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

$ lua environment-variables.lua
FOO:    nil
BAR:    nil

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

$ BAR=2 lua environment-variables.lua
FOO:    nil
BAR:    2

Next example: Exec'ing Processes.