Environment Variables in Lua

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

-- To set a key/value pair, we can use the os.setenv function.
-- To get a value for a key, we use the os.getenv function.
-- This will return nil if the key isn't present in the environment.

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

-- To list all key/value pairs in the environment, we can use the os.getenv function
-- with no arguments. This returns a table where the keys are the environment variable names.
-- Here we print all the keys.

print()
for k, _ in pairs(os.environ()) do
    print(k)
end

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

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

PATH
HOME
USER
...
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 lua environment-variables.lua
FOO: 1
BAR: 2
...

Note that in Lua, unlike some other languages, there’s no built-in way to directly modify the environment of the current process. The os.setenv function typically only affects child processes, not the current process. The exact behavior may depend on your Lua implementation and operating system.

Also, the os.environ() function is not standard in all Lua implementations. If it’s not available, you might need to use a different method to list all environment variables, possibly involving platform-specific solutions or additional libraries.