Skip to content

BirdeeHub/lua-osenv

Repository files navigation

osenv - lua module for managing os environment variables

os.getenv exists by default. os.setenv does not.

A vim.env polyfill with extra features.

require('osenv').MY_VAR = "MY_VALUE"

Installation

Using LuaRocks

luarocks install osenv

Supports all platforms, including Windows.

Using Nix

  • Flake or flakeless support, both methods return according to the flake outputs schema.
  • Overlay and packages available for Lua versions 5.1+, as well as a neovim plugin.
  • Dev shell included for building via make.

Using Make

Requires a C compiler (GCC, Clang, MinGW). If not gcc, set CC as well. Run from the root of the repository. The makefile will not work for MSVC, but the luarocks MSVC backend will work.

If you don't know where your Lua headers are, find them with:

gcc -xc -E -v - <<< '#include <lua.h>' 2>&1 | grep lua.h | head -n 1 | awk '{print $3}' | tr -d '"' | xargs dirname

Build the library:

Build outputs to DESTDIR, which defaults to ./lua, creating ./lua/osenv.so

make build LUA_INCDIR=/path/to/lua/includes

Add to Lua's package.cpath after building:

export LUA_CPATH="$LUA_CPATH;/path/to/osenv/lua/?.so"

Usage

package.cpath = package.cpath .. ";/path/to/osenv/lib/?.so"
-- mark it like this for lsp type info! (sorry, C compiled module)
---@module 'osenv.meta'
os.env = require("osenv")

-- with no arguments, returns the current environment
local oldenv = os.env()
for k, v in pairs(oldenv) do
    print(k.."="..v)
end

-- set the variable
os.env.MY_VAR = "somevalue" -- (via __newindex)
os.env { -- (via __call)
    PATH = os.env.PATH..":/home/"..os.env.USER.."/.bin",
    HOME = "/home/"..os.env.USER,
    EXTRA_VAR = "extra"
    MY_NUMBER_VAR = 1,
    MY_META_VAR = setmetatable({}, { __tostring = function(self) return "my meta var" end })
}

-- get the variable (always a string value, nil if unset)
print(os.env.MY_VAR)
print(os.env.MY_NUMBER_VAR)
print(os.env.MY_META_VAR)

-- unset the variable
os.env.MY_VAR = nil

-- set only if not already set (via __newindex)
os.env[{"MY_VAR"}] = "somevalue" -- no-op if MY_VAR exists

-- set only if not already set (via __call)
os.env({ [{"MY_VAR"}] = "somevalue" }) -- no-op if MY_VAR exists

-- Special mass unset syntax:
os.env[{}] = { "MY_NUMBER_VAR", "MY_META_VAR" } -- (this one only works for __index)

os.env(oldenv, true) -- OVERWRITE the current environment (careful!)

About

Manage lua process environment. `os.env.MY_VAR = "VAL"`

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors