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

Datastore Script Calls Nil Value?

I have this code:

local datastore = game:GetService("DataStoreService"):GetDataStore("Statistics")

game.Players.PlayerAdded:connect(function(player)
	local async = datastore:GetAsync(tostring(player.userId))
	local cash,xp = Instance.new("IntValue",player),Instance.new("IntValue",player)
	cash.Name = "Cash"
	xp.Name = "XP"
	cash.Value = async[1] --breaks here
	xp.Value = async[2]
	print(cash.Value,xp.Value)
end)

It breaks at where i said and outputs something like: async, a nil value How and why does it do this?

1 answer

✓ Accepted answer

To fix this, just add conditions if async is nil, then make a new table. Make sure you save the table to the datastore too!

local datastore = game:GetService("DataStoreService"):GetDataStore("Statistics")

game.Players.PlayerAdded:connect(function(player)
	local async = datastore:GetAsync(tostring(player.userId))
	if async == nil then --see if it's nil here
		async = {0,0} --default values of cash and xp
		datastore:SetAsync(tostring(player.userId),async) --optional to save, you could try saving when a player leaves if need to prevent data store limitations from causing a problem
	end
	local cash,xp = Instance.new("IntValue",player),Instance.new("IntValue",player)
	cash.Name = "Cash"
	xp.Name = "XP"
	cash.Value = async[1] --shouldn't break anymore :P
	xp.Value = async[2]
	print(cash.Value,xp.Value)
end)

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