Inserting data into table but having it not saved

local user = playersData[player.UserId]
if not user then return end

table.insert(user.Classes[class][itemType], item)
print(httpService:JSONEncode(user.Classes))

Shows that the item has been added to the players data table, however when the player leaves and rejoin and print this on player joining

print(httpService:JSONEncode(user.Classes))

It doesn’t show the item in the players data

function dataManager:SaveData(player)
	local saveJSON = httpService:JSONEncode(playersData[player.UserId])
	playerDataStore:SetAsync(player.UserId, saveJSON)
end

So the item is clearly being added to the players data table, but when saving and rejoining it is removed? I’m sure I’ve used table.insert in the past to add stuff to players data without any hassles

What is item?

Also, there’s no need to encode/decode JSON, because datastores already do this internally
You can just do ds:SetAsync(key, table)
Assuming the table can be appropriately converted

I also recommend printing saveJSON if you haven’t already

item is the name of the item being brought ( in this case ‘Claymore’)

When I use the print it shows [“Weapons”] = {‘Sword’, ‘Claymore’] after the table.insert is used

But when a player rejoins, it only prints the sword, not the brought item (CLaymore)

Output:
When you join
["Sword"]
When you buy the CLaymore
["Sword","Claymore"]
So it is inserting the Claymore into that list, however when you rejoin all you get is this
["Sword"]

EDIT Just did print(saveJSON) and sure enough it does seem to be saving them
[,“Weapons”:[“Sword”,“Claymore”,“Highlander”]
Just copied the section of it that is relevant, so guessing this means it’s saving, so that means that it’s loading properly then

Ok I think I know the problem now:

function dataManager:GetData(player)
	local loadJSON = playerDataStore:GetAsync(player.UserId)
	local setData = (loadJSON and httpService:JSONDecode(loadJSON)) or {}
	
	print(loadJSON)
	playersData[player.UserId] = updateObject(setData, data)
	print(httpService:JSONEncode(playersData[player.UserId].Classes.Knight.Weapons))
    	
	dataReady = true
end

loadJSON prints the saved table, with the swords in the list, however, the second print doesn’t so it has something to do with

playersData[player.UserId] = updateObject(setData, data)

Now updateObject() is

function updateObject(old, new)
    local update = {}
    for i, v in next, new do
        update[i] = (type(v) == 'table' and old[i] and updateObject(old[i], v)) or old[i] or v
    end
    return update
end

Now the point of this updateData was to check the original data table that all new players are given, and if there’s more data inside the original table then it gives it to the players who have previous data. So I can obviously remove this, but that would break everything :confused: Is there something I can change inside the updateTable? because it seems to clear whatever’s inside the saved tables

1 Like