Data cannot be added to table

I think there is no problem in script, but print(playerData[pl.UserId]) returns nil. This is some script adding table into table. Some code is changed to comment for testing. How can I solve the problem?

local playerData = {}

players.PlayerAdded:Connect(function(pl)
	--local currentData = pds:GetAsync(pl.UserId)
	--if currentData == nil then
		local data = {
			coin = 0,
			ownCards = {
				["A"] = 1
			},
			ownSkins = {},
			decks = {},
			deckEditing = {}
		}
		
		playerData[pl.UserId] = data
		print(playerData[pl.UserId])
		events.CardAmount:FireClient(pl, data.ownCards)
	--else
		--playerData[pl.UserId] = currentData
		--ownCardAmount(pl)
	--end
	
	
	events.ClockEvent:FireClient(pl, game:GetService("Lighting").ClockTime)
end)

local players = game:GetService(“Players”)

Did you define players before running the script?

Sure, and I just forgot to put it in the post. Just in case, there is no error but print(playerData[pl.UserId]) just return nil.

Can you provide the full script?

Can you provide the entire script?

Whole script would be nice.

Okay, here is the whole script. But I think it is indifferent to the problem…


local players = game:GetService("Players")
local sStorage = game:GetService("ServerStorage")
local rStorage = game:GetService("ReplicatedStorage")
local events = rStorage:WaitForChild("RemoteEvents")
local functions = rStorage:WaitForChild("RemoteFunctions")
local http = game:GetService("HttpService")


local mss = game:GetService("MemoryStoreService")
local ms1 = mss:GetSortedMap("GameMode1")
local ms = game:GetService("MessagingService")
local serverid = game.JobId
local isserverhost = false
local dss = game:GetService("DataStoreService")
local serverhostforwhatmode = ""
local ds1 = dss:GetDataStore("HostServerData")
local pds = dss:GetDataStore("PlayerDataStore")
local numberofplayersperround = 2 -- keep it as any number you want
local tps = game:GetService("TeleportService")
local cardModule = require(sStorage.AllCards)
local playerData = {}


-- if your teleporting a player to that place if they get confirmed
local placeid = 000 --

local dataretrived = ds1:GetAsync("HostData")


local DRAWNUM = 1

local player = players:GetChildren()

--マッチング待機場所
local function checkforconfirmedqueue(gamemode)
	if isserverhost == true then
		local playerlist = ms1:GetRangeAsync(Enum.SortDirection.Descending,2)
		if #playerlist == numberofplayersperround then
			local createdplaceid = tps:ReserveServer(placeid)
			local missingplayertable = {}
			local playerstobeteleported = {}
			for i,v in pairs(playerlist) do
				if game.Players:FindFirstChild(v) then
					table.insert(playerstobeteleported,game.Players:FindFirstChild(v))
				else
					table.insert(missingplayertable,v)
				end
			end
			tps:TeleportToPrivateServer(placeid,createdplaceid,playerstobeteleported)
			if #playerstobeteleported < numberofplayersperround then
				ms:PublishAsync("teleportplayer",{["ServerId"] = createdplaceid,["Players"] = missingplayertable})
			end
		end
	else
		if dataretrived[gamemode] == nil then
			isserverhost = true
			dataretrived[gamemode] = serverid
			ds1:UpdateAsync("HostData",dataretrived)
			ms:PublishAsync("updatedata",dataretrived)
		end
	end
end

ms:SubscribeAsync("updatedata",function(message)
	dataretrived = message.Data or ds1:GetAsync("HostData")
	-- update the host data of servers when host is changed
end)

ms:SubscribeAsync("teleportplayer",function(message)
	local playerlist = message.Data["Players"]
	local serverid = message.Data["ServerId"]
	for i,v in pairs(playerlist) do
		if game.Players:FindFirstChild(v) then
			-- if that player is in the game, then teleport him to the round
			tps:TeleportToPrivateServer(placeid,serverid,game.Players:FindFirstChild(v))
		end
	end
end)

local function addplrtoqueue(plr,mode)
	if plr:GetAttribute("IsInQueue") == true then
		return
	end
	plr:SetAttribute("IsInQueue", true)
	if mode == "GameMode1" then
		ms1:SetAsync(plr.Name,game.JobId, 300)
	end
	checkforconfirmedqueue(mode)
end

rStorage.Matching.Event:Connect(function(plr,gamemode)
	addplrtoqueue(plr,gamemode)
end)
-- removing the server as host when server is closing
game.Players.PlayerRemoving:Connect(function(plr)
	if isserverhost == true and #game.Players:GetPlayers() <= 1 then
		dataretrived[serverhostforwhatmode] = nil
		ms:PublishAsync(dataretrived)
	end
	-- if player is in queue, remove him from the queue
	if plr:GetAttribute("IsInQueue") == true then
		ms1:RemoveAsync(plr.Name)
	end
end)

events.SearchBattle.onServerEvent:Connect(function(pl)
	rStorage.Matching:Fire(pl, "GameMode1")
	events.AttemptMatching:FireClient(pl, true)
	
	
end) 

events.CancelMatch.OnServerEvent:Connect(function(pl)
	local success, remove = pcall(function(pl)
		ms1:RemoveAsync(pl.Name)
		pl:SetAttribute("IsInQueue", false)
		return true
	end)
	
	if success and remove == true then
		events.CancelMatch:FireClient(pl, true)
	else
		events.CancelMatch:FireClient(pl, false)
	end
		
end)

local function detectdeck(pl, ID)
	local data = playerData[pl.UserId]
	for _, D in ipairs(data.decks) do
		if ID == D.deckID then
			return D
		end
	end
	return nil
end

--カード所持数を通知
local function ownCardAmount(pl)
	local data = playerData[pl.UserId]
	events.CardAmount:FireClient(pl, data.ownCards)
end

--カードの情報渡す
functions.ShowText.OnServerInvoke = function(pl, Name)
	
	for _, t in ipairs(cardModule) do
		local check = false
		if Name == t.Name then
			check = true
			return {
				Name = t.Name,
				Type = t.Type,
				Cost = t.Cost,
				Habitat = t.Habitat,
				Attack = t.Attack,
				Health = t.Health,
				Defense = t.Defense,
			}
			
		end
		
	end
	return nil
end

--デッキからカードを抜く
functions.RemoveDeck.OnServerInvoke = function(pl, cardName, cardAmount)
	local data = playerData[pl.UserId]
	local amount = data.ownCards[cardName]
	if amount > cardAmount then
		return true
	else
		return nil
	end
end


--デッキにカードを追加
functions.AddDeck.OnServerInvoke = function(pl, cardName, cardAmount)
	local data = playerData[pl.UserId]
	local amount = data.ownCards[cardName]
	if amount > cardAmount then
		return true
	else
		return nil
	end
end

--デッキをセーブ
functions.SaveDeck.OnServerInvoke = function(pl, deck, Name)
	if Name == nil or type(Name) ~= string then
		return nil
	end
	
	
	local data = playerData[pl.UserId]
	
	if data == nil then
		return nil
	end
	
	
	--名前被り防止
	for i=1, #data.decks do
		if data.decks[i].deckName == Name then
			return "Same"
		end
	end
	
	--カードがあるか確認
	local check = function()
		for card, amount in pairs(deck) do
			return false
		end
		return true
	end
	
	if check() == true then
		return nil
	end
	
	local shortage = {}
	
	--カード不足を計算
	for cardName, deckCount in pairs(deck.cards) do
		local gap = data.ownCards[cardName] - deckCount
		
		if gap < 0 then
			shortage[cardName] = -gap
		end	
		
	end
	
	local empty = function()
		for card, num in pairs(shortage) do
			return false
		end
		
		return true
	end
	
	if empty() == false then
		return shortage
	else
		--既にデッキがあるか、新しいものか確認
		local detect = detectdeck(pl, deck.deckID)
		
	
		if detect == nil then
			table.insert(data.decks,{
				deckName = Name,
				deckID = http:GenerateGUID(),
				cards = deck.cards,
				cardSkin = nil,
				keyCard = {}
			} ) 
			
		else
			detect.deckName = Name
			detect.cards = deck.cards
			
			
		end
		
	
		return true
	end
	
	
end

--デッキをクライアントに送る
functions.SerchDecks.OnServerInvoke = function(pl)
	print(playerData[pl.UserId])
	return playerData[pl.UserId].decks
end

--選択されたデッキがあるか確認
functions.DetectDeck.OnServerInvoke = function(pl, ID)
	if detectdeck(pl, ID) ~= nil then
		playerData[pl.UserId].deckEditing = detectdeck(pl, ID)
		return true
	else
		return nil
	end
	
end




--データをロード
players.PlayerAdded:Connect(function(pl)
	--local currentData = pds:GetAsync(pl.UserId)
	--if currentData == nil then
		local data = {
			coin = 0,
			ownCards = {
				["A"] = 1
			},
			ownSkins = {},
			decks = {},
			deckEditing = {}
		}
		
		playerData[pl.UserId] = data
		print(playerData[pl.UserId])
		events.CardAmount:FireClient(pl, data.ownCards)
	--else
		--playerData[pl.UserId] = currentData
		--ownCardAmount(pl)
	--end
	
	
	events.ClockEvent:FireClient(pl, game:GetService("Lighting").ClockTime)
end)


while true do
	for i=1, 120 do
		wait(5)
		game:GetService("Lighting").ClockTime += 0.1
	end
	events.ClockEvent:FireAllClients(game:GetService("Lighting").ClockTime)
	
	
end


while true do
	task.wait(10)
	
	for UserId, data in pairs(playerData) do
		print("Saved".. UserId)
		local success, save = pcall(function()
			pds:UpdateAsync(UserId, function(oldData)
				return data
			end)
		end)
		
		for _, pl in ipairs(game:GetService("Players"):GetChildren()) do
			if pl.UserId == UserId then
				if success then
					
					events.AutoSave:FireClient(pl, true)
				
				
				else
					events.AutoSave:FireClient(pl, nil)
				end
			end
		end
		
		
		
	end
	
	
end

Put both of these in their own thread (task.spawn()) as the second while true loop will never run.

2nd: I have no idea and this shouldn’t be happening. Could you try debugging more by adding more print statements in the PlayerAdded event?

As what others have said here, your code works fine on our end. Your provided full code is too long for us to read. Can you pinpoint exactly in which part of your code handles the playerData table? So far, the only code that does this is the one you have provided in your main post.

It’d be extremely useful if you can learn how to use the debugging tools available in studio, particularly the breakpoints and watch window, as both of these features allow you to pause execution of code at any line you wish to place, run or skip a specific code line, and tracks the value of each variable.

In my script, playerData is mainly used for store player’s Data, and edit it or check player’s action. (RemoteFunction.onServerInvoke)

My post may be misleading, so I tell you that not only print() but also anything calling playerData[something] get nil. Here example:

when client invoke SerchDecks, playerData[pl.UserID.decks] return nil.

This might be due to the client calling the functions before the player is loaded. Try waiting until the data is loaded then invoke any remote functions.

I also recommend using profilestore datastore wrapper to handle data.

I just tried RemoteEvent and it worked! Thanks for your(and others’) support!