Help Saving Data From a ModuleScript

Hey! So I’m trying to make a clothing shop that saves the player owned clothing, I have a local script, a server script, and a module script. I’ll just include the important bits of my server script and module script to save you time but if you need more let me know!

So essentially my issue is; I’m trying to save data, but it seems that it’s not saving properly, am I doing something incorrectly? The goal is to add items to a table when the player purchases them, then save that table to a datastore.

UPDATE: It looks like it’s saving properly, however, when I try to load the data, it’s printing as a {} empty table even when it has items in it.

Here’s my module script:

local ownedItems = {}

local module = {}

function module.AddOwnedItem(player, itemName)
	ownedItems[player.UserId] = ownedItems[player.UserId] or {}
	ownedItems[player.UserId][itemName] = true
	print(ownedItems[player.UserId])
end

function module.GetOwnedItems(player)
	print(ownedItems[player.UserId])
	return ownedItems[player.UserId] or {}
end

function module.ResetOwnedItems(player, playerOwnedStuff)
	for i,playerownedItem in pairs(playerOwnedStuff) do
		ownedItems[player.UserId] = ownedItems[player.UserId] or {}
		ownedItems[player.UserId][playerownedItem] = true
	end
end
return module

And here’s the important part of my server script:

local players = game:GetService("Players")
local dss = game:GetService("DataStoreService")
local ds = dss:GetDataStore("ownedClothing")

local OwnedItemsModule = require(game.ReplicatedStorage.OwnedItemsModule)

function loadPlayerData(player)
	local success, error_message = pcall(function()
		local data = ds:GetAsync(player.UserId.."-ownedclothes") or {}
		print(data)

		game.ReplicatedStorage.GetData:FireClient(player, data)
		OwnedItemsModule.ResetOwnedItems(player, data)
	end)
	
	if not success then
		print('error:', error_message)
	end
end

game.Players.PlayerAdded:Connect(function(player)
	local ls = Instance.new("Folder")
	ls.Name = "leaderstats"
	ls.Parent = player

	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Parent = ls
	cash.Value = 1000

	loadPlayerData(player)
end)

game.Players.PlayerRemoving:Connect(function(player)
	local success, error_message = pcall(function()
		print('1')
		local ownedItems = OwnedItemsModule.GetOwnedItems(player)
		ds:SetAsync(player.UserId.."-ownedclothes", ownedItems)
		print('2')
		print('success')
	end)
	
	if not success then
		print('Error: ', error_message)
	end
end)

Figured out it had to do with the way I was testing it, it does work.

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