tm_cache
tm_cache is a lightweight cross-resource volatile key-value store for the server and the client. Data is partitioned by the calling resource, so you never supply a namespace and one resource cannot overwrite another's keys. Data lives in memory only, so it survives a resource restart but not a server or game restart.
The usual use is carrying expensive in-memory state across a restart of your own resource.
Requirements
| Needs | Notes |
|---|---|
tm_lib | The Twilight Moon library: logging and the update check. |
ox_lib | Installed next to tm_lib, which depends on it. |
Install
Put tm_cache in your resources folder and start it after tm_lib:
ensure ox_lib
ensure tm_lib
ensure tm_cacheConsumers get a handle with tm.exports.get, which waits for tm_cache to start, so the order against your own resources does not matter.
Settings
tm_cache has no settings.
Exports
Every export exists on both the server and the client. The two caches are independent, nothing is synced between them.
local cache = tm.exports.get('tm_cache')| Export | Description |
|---|---|
set(key, value) | Stores value under key for the calling resource. A nil value removes the key. |
get(key) | Returns the value stored under key for the calling resource, or nil. |
getAll() | Returns a shallow copy of every key and value stored for the calling resource. |
clear(key?) | Removes one key, or the whole namespace of the calling resource when no key is given. |
clearAll(resourceName) | Removes the whole namespace of a named resource. For cleanup and admin tools. |
flush() | Removes every namespace. For admin and debug use only. |
cache:set('myKey', { id = 1, name = 'foo' })
local value = cache:get('myKey')
local all = cache:getAll()
cache:clear('myKey') -- one key
cache:clear() -- everything this resource stored
cache:clearAll('vehicles')
cache:flush()The namespace comes from the resource that makes the call, so a resource can only read and write its own data through set, get, getAll and clear. clearAll and flush reach other resources' data on purpose.
Keeping state across a restart
Save into the cache when your resource stops and restore it when it starts again:
local cache = tm.exports.get('tm_cache')
AddEventHandler('onResourceStop', function(resourceName)
if resourceName ~= GetCurrentResourceName() then return end
cache:set('myState', Server.myState)
end)
CreateThread(function()
local saved = cache:get('myState')
if not saved then return end
Server.myState = saved
cache:clear('myState')
end)Languages
tm_cache has no player or staff text.
Changelog
| Version | Notes |
|---|---|
| 0.1.1 | The console prefix uses the Twilight Moon colors. |
| 0.1.0 | Runs on tm_lib: logging through tm.log, the update check, the Twilight Moon manifest and docs. Calls made from tm_cache itself use its own namespace instead of failing on a missing resource name. |
| 0.0.1 | First release. |