DataStoreService Issues - lua

bear with me but this is my first post so unsure of general formats etc.
I am currently testing with my first data store system on ROBLOX. After following a tutorial I managed to get a data store to store, load and save a cash value specified to the userID that went into the leaderboard. I am currently trying to edit the system to work with a value saved to the player, rather than a leaderstat value but it doesn't seem to be either loading or saving the value correctly.
If you take a look at the code below it is set up to print out strings to confirm the saving/loading has worked but it does not either load or save the value correctly.
Currently the script loads the value and a separate localscript displays the value as text to a display gui with two buttons than can either increase or decrease the value.
I am very new to ROBLOX Lua, so any help would be greatly appreciated.
Script located within ServerScriptService:
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("DataStore")
local data2
game.Players.PlayerAdded:Connect(function(player)
local SusTune = Instance.new("Folder")
SusTune.Name = "SusTune"
SusTune.Parent = player
local fcamber = Instance.new("IntValue")
fcamber.Name = "fCamber"
fcamber.Parent = SusTune
local success, errormessage = pcall(function()
data2 = myDataStore:GetAsync(player.UserId.."-FC")
end)
if success then
fcamber.Value = data2
print("Successfully loaded data!")
print(fcamber.Value)
else
warn(errormessage)
print("There was an error while getting your data.")
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall(function()
myDataStore:SetAsync(player.UserId.."-FC",player.SusTune.fCamber.Value)
end)
if success then
print("Data saved successfully!")
else
print("There was an error when saving data.")
warn(errormessage)
end
end)
LocalScript located within gui button:
local counterDisplay = script.Parent
local increaseButton = script.Parent.Parent.Increase
local decreaseButton = script.Parent.Parent.Decrease
local counter = game.Players.LocalPlayer.SusTune.fCamber.Value
counterDisplay.Text = counter
increaseButton.MouseButton1Click:Connect(function()
print("+1 added")
counter += 1
game.Players.LocalPlayer.SusTune.fCamber.Value = counter
counterDisplay.Text = counter
end)
decreaseButton.MouseButton1Click:Connect(function()
print("-1 added")
counter -= 1
game.Players.LocalPlayer.SusTune.fCamber.Value = counter
counterDisplay.Text = counter
end)
I have personally tried comparing this version to the working cash version but cannot work out why its not working. If its something really silly or simple I am going to hate myself and feel like an idiot, but been staring at it for an hour so need some help. Many thanks in advance :)
EDIT:
I think I have managed to narrow down the error.
When running the game and using console the buttons do not change the fCamber.Value BUT when running it in studio you can visually see the value changing with each button click, also confirmed by the ‘+/-1 added’ which is outputted in both studio and Roblox console.
After using SetASync in the main script, I had the script output the value it had just saved using a GetASync immediately afterwards (for testing purposes) and it seems the value itself is not saving to the data store.
I’m not sure if this extra data will benefit or not, but thought it would be a good detail to add.
z32

Related

The door data is not saved in Roblox

I wrote a door save system.
That is, if the user previously bought them, then when re-entering the game, they must be open.
My code works, but the door doesn't save at all.
-- DoorsDataStore
-- Save Stats Doors
local opend = false
local datastorage = game:GetService("DataStoreService")
local isitopen_1 = datastorage:GetDataStore("Door")
game.Players.PlayerAdded:Connect(function(player)
local boolValueDoors = Instance.new("Folder")
boolValueDoors.Name = "BoolValueDoors"
boolValueDoors.Parent = player
local door_1 = Instance.new("BoolValue")
door_1.Parent = boolValueDoors
door_1.Name = "BoolValueDoor_1"
door_1.Value = isitopen_1:GetAsync(player.UserId)
print("True or False")
print(player.BoolValueDoor_1.Value)
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, erromsg = pcall(function()
isitopen_1:SetAsync(player.UserId, player.BoolValueDoor_1.Value)
end)
if erromsg then
warn("Error")
end
end)
-- TouchDoor
script.Parent.Touched:Connect(function(hit)
local humanoid = hit.Parent:FindFirstChild("Humanoid")
if (humanoid ~= nil) then
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player.leaderstats.Coins.Value >= script.Parent.Price.Value then
player.leaderstats.Coins.Value -= script.Parent.Price.Value
player.leaderstats.Level.Value += 1
script.Parent:Destroy()
player.BoolValueDoors.BoolValueDoor_1.Value = true
print("Save Door")
end
end
end)
I tried writing this code in different ways, in different versions, tried through validation. My code still doesn't do what I want.
There are multiple possible problems I see:
1.
SetAsync takes a string as the first argument, you are giving it a number value. To fix this use tostring(player.UserId)
2.
When the player first joins, the value will be set to nil, because there is no data in the datastore under the UserId, and nil is not a boolean.
I’m not sure if these are actual issues and I currently cannot check if these are real problems because I’m not on my computer but they may be something you want to change.
Also it would be nice to know if you encountered any errors when executing the code.
You should also make trigger a remote event that opens the door on the clientside in the PlayerAdded function if the value is true.

problem with getting data from dataStore in roblox

a question about Roblox studio, or rather, about dataStore. If you save the values directly in the script by the pointsStore:SetAsync ("Mars", 19) when outputting data:GetCurrentPage() - this value is output, but if you do this via a function, the value is saved, but does not appear when the data:GetCurrentPage(). How can I save user data?
save the values directly in the script:
PlayerPoints:SetAsync("Mars", 19)
local success, err = pcall(function()
local Data = PlayerPoints:GetSortedAsync(false, 5)
local WinsPage = Data:GetCurrentPage()
print(WinsPage)
end)
save the values directly in the function:
local function givePointsPlayer(player, points)
local pointsOld = pointsStore:GetAsync(player.Name.."&"..tostring(player.UserId).."&"..tostring(os.date("*t").month))
if (pointsOld == nil) then
pointsOld = 0
end
print(pointsOld)
local success, err = pcall(function()
pointsStore:SetAsync(
player.Name.."&"..tostring(player.UserId).."&"..tostring(os.date("*t").month),
pointsOld + points
)
end)
end
EventEditPointsPlayer.OnServerEvent:Connect( function(player, points)
givePointsPlayer(player, points)
end)
answer:
answer
how do I need to save user data so that it is output via :GetCurrentPage() ??
If you want to get the data from the pages, you need to write some code to go through each entry and page. Here's an example from the DevHub tutorial:
-- Sort data into pages of three entries (descending order)
local pages = characterAgeStore:GetSortedAsync(false, 3)
while true do
-- Get the current (first) page
local data = pages:GetCurrentPage()
-- Iterate through all key-value pairs on page
for _, entry in pairs(data) do
print(entry.key .. ":" .. tostring(entry.value))
end
-- Check if last page has been reached
if pages.IsFinished then
break
else
print("----------------")
-- Advance to next page
pages:AdvanceToNextPageAsync()
end
end
For more information, see this tutorial from Roblox DevHub: https://developer.roblox.com/en-us/articles/Data-store

How do I use file.Write and file.Read to save player data

Im trying to make an experience script. The only thing I can't seem to figure is Data Saving. Im using file.Write and whenever I have my script read the player's level and experience from the data, it doesnt show up. I have my variables xp equal to 0 and level equal to 1. If I wanted to save the number I assigned or any number added to this to equal a new one to a txt file using file.Write as well as having that data read whenever a player spawns, how could I accomplish this?
local xp = 0
local level = 1
local players = player.GetAll()
for k ,v in pairs(players) do
file.Write("xpdata.txt", xp)
file.Write("leveldata.txt", level)
end
hook.Add("PlayerSpawn", "leveldata", function()
file.Read("xpdata.txt", "DATA")
file.Read("leveldata.txt", "DATA")
end)
I think you need to use json.
I can't write now a whole example but you can have a look at this page https://wiki.gideros.rocks/index.php/Start_Here#Save.2Fread_data_persistently
maybe that can help you understand the concept.
What do you expect to happen if you just read a file into nirvana?
hook.Add("PlayerSpawn", "leveldata", function()
file.Read("xpdata.txt", "DATA")
file.Read("leveldata.txt", "DATA")
end)
Here you read two files but you don't do anything with the return values.
file.Read returns a string with the files contents if successful.
You need to do something with the return value.
local xpData = file.Read("xpdata.txt", "DATA")
if not xpData then
print("Reading data/xpdata.txt failed!")
else
print("XP: ", xpData)
end
Of course you should store that data per player and make sure each player gets its own xp assigned.
local xp = 0
local level = 1
local players = player.GetAll()
for k ,v in pairs(players) do
file.Write("xpdata.txt", xp)
file.Write("leveldata.txt", level)
end
This doesn't make too much sense as well.
You're writing to the same file for every player. Each loop cycle will overwrite the file of the cycle before.
Also having the same xp and level for each player won't help much.
So either you have one file per player or you have some kind of structure in that common file that allows you to write and read player specific data.
You need to "serialize" your data befor you write it to the file and deserialize it later.
This can be achieved by using two utility functions
https://wiki.facepunch.com/gmod/util.TableToJSON
https://wiki.facepunch.com/gmod/util.JSONToTable
Then you can do something like this
local playerData = {}
-- for each player
for k, player in pairs(players) do
-- add a table with xp and lvl so you can later access it by AccountID
playerData[player.AccountID] = {xp = player.xp, lvl = player.lvl}
end
local jsonStr = util.TableToJSON(playerData)
file.Write("playerdata.xp", jsonStr")
I'll leave the rest up to you so you can learn something.

Roblox In-Game Ban System

I am trying to make an in-game system for banning players. I have a button that fires a remote event with a player's name and a message for why they were banned. But every time I hit the button, I get this error :
ServerScriptService.Event_Handler:21: attempt to call a nil value
I have no idea why this is not working can someone help me understand what's going wrong?
EVENT_HANDLER
local dss = game:GetService("DataStoreService")
local bands = dss:GetDataStore("banDataStore")
BanPlayer.OnServerEvent:Connect(function(player, playertoban, reason)
local pui = player.UserId
local success, errormessage = pcall(function()
bands:SetAsync("Banned-", pui, true)
end)
if success then
print("Player Successfuly Banned")
end
game.Players:FindFirstChild(playertoban):Kick(reason)
end)
Since you are searching for players by name, it's possible that you could be spelling the name wrong. In that case, game.Players:FindFirstChild() will return nil. You can sanitize this call by making sure that the player exists before calling Kick()
Also, as a side note, it looks like you are banning the player that calls the BanPlayer RemoteEvent, not the one whose name is stored in playertoban.
local dss = game:GetService("DataStoreService")
local bands = dss:GetDataStore("banDataStore")
BanPlayer.OnServerEvent:Connect(function(player, playertoban, reason)
-- check that playertoban is a real player's name
local bannedPlayer = game.Players:FindFirstChild(playertoban)
if not bannedPlayer then
warn("Could not find a player named " .. playertoban)
return
end
-- record their user-id so we can ban them when they rejoin
local pui = bannedPlayer.UserId
local success, errormessage = pcall(function()
bands:SetAsync("Banned-", pui, true)
end)
if success then
print(playertoban .. " Successfully Banned")
else
warn(string.format("Failed to ban %s permanently with error : %s", playertoban, errormessage))
end
-- remove them from the game
bannedPlayer:Kick(reason)
end)

attempt to index nil with 'leaderstats' in roblox studio

local garbage = game.Teams["Glizzy Garbage"]
local player = game.Players.LocalPlayer
if player.leaderstats.Pounds.Value <= 1000 then --this is the line that the output is detecting the error
player.Team = garbage
end
I am trying to make it where when the player reaches a certain amount of 'pounds' then they will automatically receive a roll. I've searched through many youtube videos and haven't found a fix or an alternative way to do this, and I'm not sure why this isn't working. This script is located in the workspace. All help is appreciated.
The LocalPlayer object is only exposed in LocalScripts. Because you're using a Script in the Workspace, you'll have to access the player object another way. It's also a good idea to handle this kind of logic inside a function that is fired any time the Pounds value changes.
Try using the game.Players.PlayerAdded signal :
local garbage = game.Teams["Glizzy Garbage"]
game.Players.PlayerAdded:Connect(function(player)
local Pounds = player.leaderstats.Pounds
Pounds.Changed:Connect(function(value)
if value <= 1000 then
player.Team = garbage
end
end)
end)
Mine is just
local plrStage = plr.leaderstats.Stage.Value
try instead of putting team name put team colour
also use
player.Team.Service = garbage
end)

Resources