Hi
I added promo codes to my game and everything is done except checking if the player has redeemed it already. I know I have to use a data store but I need to save a table of used codes under player’s data store key. Or is there a different way of doing it?
I would say the table option is the best option overall. I’d go with that.
It’s best to keep data pertaining to a single player contained within the same dictionary, just do something like the following.
local playerData = {
["Data"] = {},
["RedeemedCodes"] = {"CODE1", "CODE2"}
}
Thank you, could please show me a code snippet of how would I implement it. I’m sorry I’m new to data stores and I couldn’t find any well explained posts/videos.
I started with this:
local dataStore = DataStoreService:GetDataStore("LuckyFightersX")
local Players = game:GetService("Players")
local function setUp(player)
local userId = Players.userId
local key = "UsedCodes_" .. userId
local usedCodesData = dataStore:GetAsync(key)
end
Players.PlayerAdded:Connect(setUp)
It’s from a devforum tutorial post.
local function saveData(player)
local userId = player.UserId
local key = "UsedCodes_" .. userId
local dataToSave = {
["Data"] = {},
["RedeemedCodes"] = {"CODE1", "CODE2"}
}
dataStore:SetAsync(key, dataToSave)
end
Thank you so much, can I ask what is the [“Data”] = {} for?
The [“Data”] = {} simply represents any other data you’re saving. It doesn’t have to be just one key for the rest of the data, it’s just a filler I put in.
I think the table is the best option to save a list of data
Also how would I get back this data. If after the server checks the code is valid I want to add that code to the table, how would I go about it? Or access other saved values since it’s all under 1 key?
If the code is valid, you would simply do a table.insert()
into the list of codes. As for accessing it, I would reccomend putting this data in a dictionary when the set up function is called. For an example:
local dataStore = game:GetService("DataStoreService"):GetDataStore("LuckyFightersX")
local Players = game:GetService("Players")
local playerDict = {}
local function setUp(player)
local userId = Players.userId
local key = "UsedCodes_" .. userId
local usedCodesData = dataStore:GetAsync(key)
-- Get the dictionary from usedCodesData, I forget how with regular datastores, I use datastore2. I will call the data DATA in the script.
playerDict[player] = DATA
end
local function saveData(player)
local userId = player.UserId
local key = "UsedCodes_" .. userId
local dataToSave = {
["Data"] = {},
["RedeemedCodes"] = {"CODE1", "CODE2"}
}
dataStore:SetAsync(key, dataToSave)
playerDict[player] = nil
end
Players.PlayerAdded:Connect(setUp)
Players.PlayerRemoving:Connect(saveData)