Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I stop this value from being nil?

So I used this guide to learn datastore. I keep getting 13:41:16.994 - ServerScriptService.Stat_Saver:24: attempt to index local 'data' (a nil value)

local DSS = game:GetService("DataStoreService")
local dataStore = DSS:GetDataStore("Stats", "Players")

function makeDataKey(player)
	local ret = "uid_"..player.userId
	return ret
end

function makeDataTable(player)
	local statsTable = {
		AttVal = player:findFirstChild("Data").AttVal.Value
	}
	return statsTable()
end

function savePlayerData(player)
	local key = makeDataKey(player)
	local data = makeDataTable(player)
	dataStore:SetAsync(key,data)
end

function giveDataToPlayer(player, data) 
		--The error is here
		player.Data.AttVal.Value = data.AttVal
end

function loadPlayerData(player)
	local key = makeDataKey(player)
	local data = dataStore:GetAsync(key)
	giveDataToPlayer(player, data)
end

game.Players.PlayerAdded:connect(function(player)
	wait(5)
	loadPlayerData(player)
	print("Loaded Data")
	player.Data.Level.Changed:connect(function()
		savePlayerData(player)
		print("Data saved")
	end)
end)

game.Players.PlayerRemoving:connect(savePlayerData)

1 answer

✓ Accepted answer

The error means that the data argument has been passed nil. The function is called from line 30, where the result of GetAsync is passed into data. GetAsync can be nil if you've never saved data there before. Thus, the solution is to give your script a default value, or to know what to do if data is nil. ex, on line 24 you might say = data and data.AttVal or 1, to give it a default value of 1. The "data and data.AttVal" ensures that if data is nil, data.AttVal won't be run. The "or 1" gives the expression a default value of 1. If you don't understand how to sue that, consider using an if statement instead:

if data then
	player.Data.AttVal.Value = data.AttVal
else
	player.Data.AttVal.Value = 1
end

1 comment

0

Well thanks that stops me from getting a nil value but it doesn't even save data xd. Going to find a new tutorial and try again.

This discussion is preserved as it was. New answers, comments, and votes are closed.