Attempted To Index Nil With Currency

Below is a basic Global data table but when I’m indexing with:
_G.PlayerData[plr.UserId][“Currency”][“Coins”]
I know I Can Switch It To
Currency = {
Coins = 0,
}
But would like to use the format below.

local DataTable = {
	["Currency"] = {
		["Coins"] = 0,
		["Gems"] = 0,
	},
}
_G.PlayerData = {}

game.Players.PlayerAdded:Connect(function(plr)
	local DataStore = game:GetService("DataStoreService"):GetDataStore("PlayerDatax")
	local UserData = DataStore:GetAsync(tostring(plr.UserId))

	if UserData then
		_G.PlayerData[plr.UserId] = UserData
	else
		_G.PlayerData[plr.UserId] = DataTable
	end
	
	game.Players.PlayerRemoving:Connect(function()
		DataStore:SetAsync(tostring(plr.UserId), _G.PlayerData[plr.UserId])
	end)
end)

This is because you set _G.PlayerData[UserId] etc. to data/user table, overriding it. According to your script, you can retrieve the data by doing


 _G [Userdata or Datatable][“Currency”]

_G.PlayerData[plr.UserId][“Currency”][“Coins”]

Is how I retrieve data, as stated it’s indexing non existent Table nil

One issue is that you are putting game.Players.PlayerRemoving inside of the game.Players.PlayerAdded event. You should not do this because you do not know which player is leaving, meaning you are not saving the player who left’s data for sure, unless they are the only player in the server.

Your data-saving code should be like this:

game.Players.PlayerRemoving:Connect(function(player)
    local success, reason = pcall(function()
        DataStore:SetAsync(tostring(plr.UserId), _G.PlayerData[plr.UserId])
    end)

     if not success then
        warn(reason)
     end

    -- Then remove the player's data from the table.
end)

Also, you can use UserData = UserData or DataTable instead of that if statement.

I have never worked with _G before, so I do not know if the issue is related to your use of that global variable. Have you tried replacing _G with something else?

I am aware of the removing event being inside the player event, both works the same but will move it to an external function later on, this is just 15 minutes of code so far and I’m using _G to be more organised. Grabbing the value works as is until I move it to [“format”] the issue comes around, tho it works with just format

I do not know what the problem is because I am not experiencing the “Attempted to index nil with ‘Currency’” issue with your code when I access the table. Is there another script interfering with the table?

Running,
_G.PlayerData[game.Players.Dev_Ghostt.UserId][“Currency”][“Coins”] += 100
In console
Gave me the issue

Hm, I am not sure what to say. Maybe the issue is because of the underscore in your username. Try: _G.PlayerData[game.Players["Dev_Ghostt"].UserId]["Currency"]["Coins"] += 100.

i sent u the solution in dms bro

1 Like

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