For each player changes everyones data: bug? or table feature?

local template = {Clicks = 0}

local moduleScript = require(script.Parent.ModuleScript)
local remote = game:GetService(“ReplicatedStorage”):WaitForChild(“RemoteEvent”)

game:GetService(“Players”).PlayerAdded:Connect(function(player)
print(“setting profile”)
moduleScript.SetProfile(player,template)
end)

remote.OnServerEvent:Connect(function(player)
local profile = moduleScript.GetProfile(player)
profile.Clicks += 1

print(“clic”)

for _,player in game:GetService(“Players”):GetPlayers() do
print(moduleScript.GetProfile(player))
end

end)

local uis = game:GetService(“UserInputService”)
uis.InputBegan:Connect(function(key,bool)
if key.UserInputType == Enum.UserInputType.MouseButton1 then
game:GetService(“ReplicatedStorage”):WaitForChild(“RemoteEvent”):FireServer()
end
end)

clicking from the player1 also adds clicks to player2

image
1 is player1 data
2 is player2 data

We would need to see the code for your module script.

The problem is either that your module is always returning the same table regardless of the inputted player or that they are all set to the same table.

local ProfileManager = {}

local PlayerProfiles = {}

function ProfileManager.GetProfile(Player)
return PlayerProfiles[Player.UserId]
end

function ProfileManager.SetProfile(Player, Profile)
PlayerProfiles[Player.UserId] = Profile
end

function ProfileManager.RemoveProfile(Player)
PlayerProfiles[Player.UserId] = nil
end

function ProfileManager.Output()
for i,p in PlayerProfiles do
print(i,p)
end
end

game.Players.PlayerRemoving:Connect(function(Player)
ProfileManager.RemoveProfile(Player)
end)

return ProfileManager

Where is the deepCopy function defined? Everything else looks fine.

it is not defined sorry, my bad

1 Like

Oh, the problem is that everything is referencing the template table.

You can create a shallow copy of a table using:

moduleScript.SetProfile(player, table.copy(template))

Tables act kind of like instances rather than primitive values such as strings and numbers: when you pass them around they are passed as references to a single object.

So for example, if you passes a part like so:

local template = Instance.new("Part")
template.Name = "Template"
myTable["1"] = template
myTable["2"] = template

myTable["1"].Name = "Edited"

print(myTable["2"].Name) -- Prints "Edited"

See how it modifies both? To avoid this you first need to make a copy:

local template = Instance.new("Part")
template.Name = "Template"
myTable["1"] = template:Clone()
myTable["2"] = template:Clone()

myTable["1"].Name = "Edited"

print(myTable["2"].Name) -- Prints "Template"
1 Like

thank you this helped!!! have a good day / night

1 Like