71 lines
1.9 KiB
Lua
71 lines
1.9 KiB
Lua
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
|
|
---@param callback? function Callback on value change
|
|
local function add_default_value(key, value, callback)
|
|
defaults_table=defaults_table or {}
|
|
defaults_table[key]=value
|
|
|
|
local stored_value=config:load(key)
|
|
sharedstate.init(key, value, callback)
|
|
|
|
if stored_value ~= nil then
|
|
sharedstate.queue(key, stored_value)
|
|
end
|
|
end
|
|
|
|
--- Initialize sharedconfig
|
|
-- Initialize shared config with default configuration
|
|
---@param defaults table Table containing default values
|
|
---@param callbacks? table Table containing callbacks to run on value change
|
|
function sharedconfig.load_defaults(defaults, callbacks)
|
|
logging.trace("sharedconfig.load_defaults", defaults)
|
|
for k, v in pairs(defaults) do
|
|
local callback=nil
|
|
if callbacks ~= nil and callbacks[k] ~= nil then callback=callbacks[k] end
|
|
add_default_value(k, v, callback)
|
|
end
|
|
sharedstate.commit()
|
|
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
|
|
|
|
return sharedstate.get(key)
|
|
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
|