Skip to content
This repository has been archived by the owner on Aug 20, 2022. It is now read-only.

KeyValueStore

rdev34 edited this page Aug 30, 2020 · 13 revisions

The KeyValueStore singleton class is a server-side key-value storage utility with persistence, meaning that the values are kept between server executions in the database.

In this example, every time a player sends a message we store it using KeyValueStore:Set. To retrieve the value once it has been stored, we use KeyValueStore:Get and supply a function that will be called with the value. To delete the value, we could do KeyValueStore:Delete("MostRecentChatMessage")

Events:Subscribe("ChatMessage", function(args)
    -- store the most recent chat message
    KeyValueStore:Set("MostRecentChatMessage", args.text)

    -- this is how we can retrieve the most recent chat message
    KeyValueStore:Get("MostRecentChatMessage", function(value)
        print("The most recent chat message is:", value)
    end)
end)

You might run into the use case where you want to retrieve multiple values concurrently. Rather than nesting the Get requests, you can supply a table of values to KeyValueStore:Get like this:

local keys_to_get = {"MyKey1", "MyKey2"}
KeyValueStore:Get(keys_to_get, function(values)
    local value1 = values["MyKey1"]
    local value2 = values["MyKey2"]
end)

Types supported by KeyValueStore are string, number, boolean, table (json serialization), and nil

Notes:

  1. If a key does not exist, then KeyValueStore:Get will return nil
  2. Although internally we are interacting asynchronously with a database to implement the storage for this utility, preemptive caching is used so that all changes have the appearance of immediately taking effect on the frame that KeyValueStore:Set is executed. Caching is done whenever possible and multiple outstanding Get requests for the same key are aggregated into one call to the database. In other words, the database interaction is minimized as much as possible.
Clone this wiki locally