Add sharedconfig

This commit is contained in:
NullBite 2023-06-23 02:22:20 -04:00
parent 60b57fd097
commit 49e861f3f4
Signed by: nullbite
GPG Key ID: 6C4D545385D4925A

63
sharedconfig.lua Normal file
View File

@ -0,0 +1,63 @@
local sharedconfig={}
local logging=require((...):gsub("(.)$", "%1.") .. 'logging')
local sharedstate=require((...):gsub("(.)$", "%1.") .. 'sharedstate')
sharedstate=require('nulllib.sharedstate')
local defaults_table
--- Internal; Add default value if not saved
--- Adds a value to the shared config store, falling back to a default value if
--none is stored
---@param key string Key
---@param value any Value
local function add_default_value(key, value)
defaults_table=defaults_table or {}
defaults_table[key]=value
local stored_value=config:load(key)
if stored_value == nil then
sharedstate.add(key, value)
else
sharedstate.add(key, stored_value)
end
end
--- Initialize sharedconfig
-- Initialize shared config with default configuration
---@param defaults table
function sharedconfig.load_defaults(defaults)
logging.trace("sharedconfig.load_defaults", defaults)
for k, v in pairs(defaults) do
add_default_value(k, v)
end
end
local function build_table()
local t={}
-- defaults haven't been initialized yet
if defaults_table == nil then return nil end
for k, _ in pairs(defaults_table) do
t[k]=sharedstate.get(k)
end
return t
end
--- Load config
---@param key? string Key to load
function sharedconfig.load(key)
if key == nil then
return build_table()
end
-- defaults haven't been initialized yet
if defaults_table == nil then return nil end
end
--- Save config
---@param key string Key to save
---@param value any Value to save
function sharedconfig.save(key, value)
config:save(key, value)
sharedstate.set(key, value)
end
return sharedconfig