Database Singleton by SPycre
The database singleton was made to simplify saving and loading data in your game in a safer way.
Functions
Module.new( datastore_name : string, [optional] time_out : number) : Database
Create a Database singleton instance with the provided datastore name
Database:Save( key : string, data : any, [optional] asJSON : boolean) : Tuples
Sets the key’s value to the specified data.
Database:Load( key : string, [optional] asJSON : boolean) : Tuples
Returns the function success and the data from the specified key
How to setup
The model simply contains the Instructions and the module.
Move to module somewhere inside ServerStorage.
How to use
How to initialize a singleton :
local db = require(PATHTOTHEMODULE)(DATASTORENAME, --[[optional]] time_out)
--[[ Optionally you can add the time_out parameter which
how many tries the datastore will have to load data, default is 5 ]]
How to save data :
local db = require(PATHTOTHEMODULE,DATASTORENAME)
local data = { Money = 10, XP = 5 }
local success : boolean
success, data = db:Save(KEYNAME, data, --[[optional]] asJSON)
--[[
- Optionally you can add the last parameter "asJSON" to true if you want
the data to be encoded as a JSON string (May or may not reduce data weight)
- Note that if you encode data, you will need to decode it when loading it
]]
How to load data :
local db = require(PATHTOTHEMODULE,DATASTORENAME)
local success : boolean
local data : any
success, data = db:Load(KEYNAME, --[[optional]] asJSON)
--[[
Note that if you used JSON encoding when saving data, you'll need to decode it
by adding the parameter "asJSON" to true.
]]
Example
local db = require(game.ServerStorage.Database)("datastore_name") -- Initializing datastore with name "datastore_name"
local success : boolean
local data : any
success, data = db:Load("key") -- Loading data from datastore at key "key"
if (success) then
if (data) then
print("Data exists : ".. data) -- EXPECTED OUTPUT : Data exists : 1 (only if you rerun the script)
else
print("Data doesn't exists, adding data...")
success, data = db:Save("key", 1) -- Saving 1 to datastore at key "key"
if (success) then
print("Successfully added data : ".. data) -- EXPECTED OUTPUT : Successfully added data : 1
else
print("Couldn't add data :".. data) -- EXPECTED OUTPUT : Couldn't add data : [ERROR CODE]
end
end
else
print("Couldn't load data : "..data)
end