Unknown global 'data' - DataStore

I am getting this error when I run my game. I have no idea how to script so this is why I am asking for help. This is the script:


local MyDataStore = DataStoreService:GetDataStore("MyDataStore")

game.Players.PlayerAdded:Connect(function(player)
	local stats = Instance.new("Folder")
	stats.Name = "leaderstats"
	stats.Parent = player
	
	local Clicks = Instance.new("IntValue")
	Clicks.Name = "Clicks"
	Clicks.Parent = player.leaderstats
	
	local success, errormessage = pcall(function()
		
		local data
		MyDataStore:GetAsync(player.userId.."Clicks")
	end)
	
	if success then
		Clicks.Value = data
		print("Player Data successfully saved!")
	else
		print("There was an error when saving data")
		warn(errormessage)
	end
end)

game.Players.Removing:Connect(function(player)
	
	local success, errormessage =  pcall(function()
		MyDataStore:SetAsync(player.UserId.."Clicks",player.leaderstats.Clicks.Value)
	end)
	
	if success then
		print("Player Data successfully saved!")
	else
		print("There was an error when saving data")
		warn(errormessage)
	end
	
end)```
2 Likes

This line here is the problem. You have data defined as a local variable inside another function, and so referencing it outside of it won’t work. You need to define data at the start of the script.

Hope this helps :slightly_smiling_face:

game.Players.PlayerAdded:Connect(function(player)
local stats = Instance.new(“Folder”)
stats.Name = “leaderstats”
stats.Parent = player

local Clicks = Instance.new("IntValue")
Clicks.Name = "Clicks"
Clicks.Parent = player.leaderstats
local data
local success, errormessage = pcall(function()
	

	data = MyDataStore:GetAsync(player.userId.."Clicks")
end)

if success then
	Clicks.Value = data
	print("Player Data successfully saved!")
else
	print("There was an error when saving data")
	warn(errormessage)
end

end)

This should work

2 Likes