Okay, so I'm practicing with datastores (fun) and I've made this small script:
local dss = game:GetService("DataStoreService") local ds = dss:GetDataStore("CashSaving1") game.Players.PlayerAdded:Connect(function(plr) wait(5) local cash = plr.ContainFolder.Cash.Value ds:GetAsync(plr.UserId, cash) local key = plr.UserId cash = ds:GetAsync(key) cash.Changed:Connect(function() ds:SetAsync(key, cash) end) end)
Yes, this is in a Server Script This is in ServerScriptService (I've tried placing this in other areas too, same error.) And I understand I didn't wrap it in a pcall function, not there yet, so with any code examples please don't include pcalls as it'll only make things more confusing. And no, I'm not asking for someone to make me a script. So my problem would be on line 10 .. It says the value doesn't exist.
"attempt to index local 'cash' (a nil value)"
To fetch a given entry in a datastore, you must first create said entry by saving something under a given key. You're not doing that.
(i.e. you're not calling SetAsync
before calling GetAsync
, so there's nothing to get when you call GetAsync.)
I'm assuming on Line 7 you meant to call SetAsync
and not GetAsync
.
local dss = game:GetService("DataStoreService") local ds = dss:GetDataStore("CashSaving1") game.Players.PlayerAdded:Connect(function(plr) wait(5) local cash = plr.ContainFolder.Cash.Value ds:SetAsync(plr.UserId, cash) local key = plr.UserId cash = ds:GetAsync(key) cash.Changed:Connect(function() ds:SetAsync(key, cash) end) end)
Moreover, after fixing that mistake, you might want to know that you're saving the value of cash.Value, not the cash IntValue (it's impossible to save instances directly to datastores anyway); so, there won't be such a Changed
event. You'll instead want to either create the listener beforehand or save the result to another name.
local dss = game:GetService("DataStoreService") local ds = dss:GetDataStore("CashSaving1") game.Players.PlayerAdded:Connect(function(plr) wait(5) local cash = plr.ContainFolder.Cash local savedCash = ds:GetAsync(plr.UserId) or ds:SetAsync(plr.UserId, cash.Value) -- use a ternary so that we don't write over an existing entry. local key = plr.UserId cash.Changed:Connect(function() ds:SetAsync(key, cash.Value) end) end)