From 92b4b99083293c45aa026ee19435be624f9c03f7 Mon Sep 17 00:00:00 2001 From: NullBite Date: Fri, 23 Jun 2023 16:44:28 -0400 Subject: [PATCH] Add functions to queue multiple values for sync --- sharedstate.lua | 58 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 17 deletions(-) diff --git a/sharedstate.lua b/sharedstate.lua index f7f0b91..162316f 100644 --- a/sharedstate.lua +++ b/sharedstate.lua @@ -5,9 +5,8 @@ local logging=require((...):gsub("(.)$", "%1.") .. 'logging') local is_initialized, callback_value, set_value, get_value, resolve_key, resolve_index --- list of "dirty" keys that are queued for sync. This table should be --- accessible to the entirety of the sharedstate library -local state_queued={} +--schema: similar to state_table, nested table only contains value +local state_queue={} -- we're protecting internal variables here, i'm *that* scared of writing bad -- code again. @@ -184,21 +183,46 @@ function sharedstate.set(key, value) -- pings.sharedstate_recv_named(key, value) end ----Send queued entries ---Send queued table entries to other hosts in one ping. -function sharedstate.send() - --schema: similar to state_table, nested table only contains value - local send_queue={} - -- this is intentional values in state_queued are key names - for _, key in pairs(state_queued) do - local t={ - ["value"]=get_value(key) - } - send_queue[key]=t - end +---Queue entries for sending +--Queues entries for sending over a single ping, as to prevent being rate +--limited. Values will not be accessible until sharedstate.commit() is run. +---@param key string key +---@param value any value +function sharedstate.queue(key, value) + local t={ + ["value"] = value + } + state_queue[key]=t +end - pings.sharedstate_unpack(send_queue) - state_queued={} +---Commit queued entries +--Commit queued table entries and send in one ping. +function sharedstate.commit() + --schema: similar to state_table, nested table only contains value + -- local send_queue={} + -- -- this is intentional values in state_queued are key names + -- for _, key in pairs(state_queued) do + -- local t={ + -- ["value"]=get_value(key) + -- } + -- send_queue[key]=t + -- end + + + pings.sharedstate_unpack(state_queue) + state_queue={} +end + +--- Clear a value from the shared state queue +--Clears a value from the shared state queue. If no key is specified, clears +--all queued values. +---@param key? string Key to clear +function sharedstate.clear(key) + if key ~= nil then + state_queue[key] = nil + else + state_queue={} + end end -- this can be copied directly from the internal functions as it is read only