Table's value is nil only inside of PlayerRemoving

I’m relatively new to coding on Roblox, and I’ve been trying to script a datastore for my game. I created a table to store data (worldData), but whenever I try accessing worldData it is nil inside of the PlayerRemoving part, causing the data not to be saved.

I wrote some code to fill the table with 5 placeholders, each containing the string “empty” but worldData still shows up as nil inside PlayerRemoving. I tried printing out the value of worldData inside and outside PlayerRemoving, and it correctly showed the placeholders outside PlayerRemoving but outputted nil when printed inside.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")

local dataStore = DataStoreService:GetDataStore("TestDataStore")

local worldData = {}

Players.PlayerAdded:Connect(function(player)
	local playerUserId = "player_" .. player.UserId
	
	local success, output = pcall(function()
		return dataStore:GetAsync(playerUserId)
	end)
	
	if success then
		worldData = output
	else
		warn("Error retreiving data: ", output)
	end
end)

if next(worldData) == nil then
	for i = 1, 5, 1 do
		worldData[i] = "empty"
	end
end

Players.PlayerRemoving:Connect(function(player)
	local playerUserId = "player_" .. player.UserId
	
	-- when printed here it is nil
	
	print(worldData)
	
	local success, output = pcall(function()
		dataStore:SetAsync(playerUserId, worldData)
	end)
	
	if success then
		print("Data successfully saved.")
	else
		warn("Error saving data: ", output)
	end
end)

-- when printed here it is {"empty", "empty", "empty", "empty", "empty"}

print(worldData)

Thanks for the help! :slight_smile:

It’s probably because dataStore:GetAsync(playerUserId), or rather the pcall itself, is causing worldData to be set to nil.
Try replacing

local success, output = pcall(function()
	return dataStore:GetAsync(playerUserId)
end)
	
if success then
	worldData = output
else
	warn("Error retreiving data: ", output)
end

with

local success, err = pcall(function()
	worldData = dataStore:GetAsync(playerUserId) or {}
end)
	
if not success then
	warn("Error retrieving data: ", err)
end

Also, is the code for a single player game? If not, then the code is flawed in nature and should be modified.

1 Like

Thank you! I made the mistake of thinking that the code to make the placeholders for the table would run after PlayerAdded, but it in fact ran before, causing it to get placeholders then become nil. Also, it is a single player game; thanks for the heads up!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.