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!