Moonshark/runner/lua/env.lua

90 lines
1.9 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
function env_get(key, default_value)
if type(key) ~= "string" then
error("env_get: key must be a string")
end
-- Check context for environment variables
if __ctx and __ctx._env and __ctx._env[key] ~= nil then
return __ctx._env[key]
end
return default_value
end
-- Set an environment variable
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 __ctx then
__ctx._env = __ctx._env or {}
__ctx._env[key] = value
end
-- Persist to Go backend
return __env_set(key, value)
end
-- Get all environment variables as a table
function env_get_all()
-- Return context table directly if available
if __ctx and __ctx._env then
local copy = {}
for k, v in pairs(__ctx._env) do
copy[k] = v
end
return copy
end
-- Fallback to Go call
return __env_get_all()
end
-- Check if an environment variable exists
function env_exists(key)
if type(key) ~= "string" then
error("env_exists: key must be a string")
end
-- Check context first
if __ctx and __ctx._env then
return __ctx._env[key] ~= nil
end
return false
end
-- Set multiple environment variables from a table
function env_set_many(vars)
if type(vars) ~= "table" then
error("env_set_many: vars must be a table")
end
if __ctx then
__ctx._env = __ctx._env or {}
end
local success = true
for key, value in pairs(vars) do
if type(key) == "string" and type(value) == "string" then
-- Update context
if __ctx and __ctx._env then
__ctx._env[key] = value
end
-- 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