Moonshark/runner/lua/env.lua
2025-05-30 17:45:58 -05:00

94 lines
2.0 KiB
Lua

-- Environment variable module for Moonshark
-- Provides access to persistent environment variables stored in .env file
-- Get an environment variable with a default value
-- Returns the value if it exists, default_value otherwise
function env_get(key, default_value)
if type(key) ~= "string" then
error("env_get: key must be a string")
end
-- First check context for environment variables (no Go call needed)
if _env and _env[key] ~= nil then
return _env[key]
end
return default_value
end
-- Set an environment variable
-- Returns true on success, false on failure
function env_set(key, value)
if type(key) ~= "string" then
error("env_set: key must be a string")
end
-- Update context immediately for future reads
if not _env then
_env = {}
end
_env[key] = value
-- Persist to Go backend
return __env_set(key, value)
end
-- Get all environment variables as a table
-- Returns a table with all key-value pairs
function env_get_all()
-- Return context table directly if available
if _env then
local copy = {}
for k, v in pairs(_env) do
copy[k] = v
end
return copy
end
-- Fallback to Go call
return __env_get_all()
end
-- Check if an environment variable exists
-- Returns true if the variable exists, false otherwise
function env_exists(key)
if type(key) ~= "string" then
error("env_exists: key must be a string")
end
-- Check context first
if _env then
return _env[key] ~= nil
end
return false
end
-- Set multiple environment variables from a table
-- Returns true on success, false if any setting failed
function env_set_many(vars)
if type(vars) ~= "table" then
error("env_set_many: vars must be a table")
end
if not _env then
_env = {}
end
local success = true
for key, value in pairs(vars) do
if type(key) == "string" and type(value) == "string" then
-- Update context
_env[key] = value
-- Persist to Go
if not __env_set(key, value) then
success = false
end
else
error("env_set_many: all keys and values must be strings")
end
end
return success
end