Data - tayjay/SCriPt GitHub Wiki

Everything that your script has done so far is lost when the server restarts. If you want to keep data around between restarts, you need to save it to a file. This is called persistence. Here is an example of how you can save data to a file and load it back up when the server starts.

Saving

The plugin handles this automatically. Any change made to the store returned by Data.Get(...) is written to a JSON file in the Data folder, named after the key you passed to Get. No manual saving is required. Writes are debounced — a burst of changes is coalesced into a single write a moment later, and any pending changes are flushed automatically when the script unloads or the server shuts down.

Immutable Data

If you want to store data that should only be set once (such as config defaults), prefix the key with an underscore _ or a dot .. Once set, that key can no longer be overwritten — later assignments to it are silently ignored. For example:

config_example = SCriPt.Module('ConfigExample')
config_example.data = Data.Get('config_example')
config_example.data['_enabled'] = true -- Set once; further writes to '_enabled' are ignored

Example

-- Create a module to hold our script functions
storage_example = SCriPt.Module('StorageExample')
storage_example.data = Data.Get('storage_example')

function storage_example.load()
    -- mod.on auto-removes the listener when the script unloads.
    storage_example.on(Events.Server.WaitingForPlayers, storage_example.onWaitingForPlayers)
end

function storage_example.onWaitingForPlayers()
    -- Increment the count whenever a new round is starting up
    if storage_example.data['count'] == nil then
        storage_example.data['count'] = 0
    end
    storage_example.data['count'] = storage_example.data['count'] + 1
    print("Waiting for players has happened " .. storage_example.data['count'] .. " times.")
end

What you can store

The store is backed by JSON, so values must be JSON-friendly. When you assign a value it is copied into the store. The following types are supported:

  • String
  • Number (int/float/double)
  • Boolean
  • Table (including nested tables — they are copied in automatically)
  • Nil (removes the key)

Functions, coroutines, and userdata (Players, Vectors, etc.) cannot be stored and will raise an error. Store a plain representation instead — for example, save a player's UserId string rather than the Player object.

Storing a table

Whole tables (including nested ones) can be stored in a single assignment:

table_example = SCriPt.Module('TableExample')
table_example.data = Data.Get('table_example')

table_example.data['last_round'] = {
    winner = 'ClassD',
    duration = 320,
    survivors = { 'Alice', 'Bob' }
}

-- Read it back later:
print(table_example.data['last_round'].winner)