Having trouble with storing player data in a ModuleScript

Hey DevForum members, hoping you had a good day.

I’m having a problem with storing data in a table inside a ModuleScript.
I used to use Values inside the player for actual data saving. I decided to move to tables in ModuleScripts to manage the data. However I noticed a problem when importing the data.

-- Module Script
local module = {}

module.Players = {}

function module:ImportUserData(Player,Data)
	local UserData = {
		UserId = Player.UserId,
		Money = Data.Money,
		["InventoryData"] = {},
		["ShopData"] = {},
	}
	table.insert(module.Players,UserData)
end

function module:ExportUserData(Player)
	local UserData
	for i,v in ipairs(module.Players) do
		if v.UserId == Player.UserId then
			UserData = {
				Money = v.Money,
				["InventoryData"] = {},
				["ShopData"] = {},
			}
			table.remove(module.Players,i)
			return UserData
		end
	end
end

function module:GetUserData(Player)
	for i,v in ipairs(module.Players) do
		if v.UserId == Player.UserId then
			return v
		end
	end
end

return module
-- Server Code on a RemoteFunction
local BaseModule = require(script.Parent)

function Test(Player)
	local UserData = {
		Money = 50,
	}
	BaseModule:ImportUserData(Player,UserData)
end
	
game.ReplicatedStorage.ReplicatedRemotes.LoadData.OnServerInvoke = Test

If I go into accurate solo, call the RemoteEvent from the script or the Command Bar, switch to Server, and try to get that data, it won’t exist. However, if I call the module :ImportUserData() function directly from the command bar (on the server) , it’ll exist. I’m assuming somethings wrong with the RemoteFunction?

Any help would be appreciated.

It looks like you forgot the return the table in the server test function.


function Test(Player)
    local UserData = {Money = 50};
    BaseModule:ImportUserData(Player,UserData);
    return UserData;
end
1 Like

Thanks for the return part, however this isn’t what the function is supposed to do. It’s basically PlayerAdded but waiting for the User to actually join and press play opposed to auto loading in.
Using RemoteFunction instead of RemoteEvent because it’s supposed to load the Data on the server and possibly return any warnings or heads up to the client about data if it fails to load.

The problem is module.Players table isn’t adding the Data when :ImportUserData is called by RemoteFunction opposed to calling the function directly from the module.

I think part of the issue might be with your testing method, the command bar – AFAIK the command bar runs in a different environment than the server and the client (or at least, in terms of ModuleScript caching, doesn’t cache) so could be returning a completely different table than what the server scripts are using.

The solution would be to integrate all of your tests into the scripts themselves (some prints will do).

5 Likes

Thanks! I had no idea and thought I was doing something wrong. I was going to reply earlier but I was in school.