ModuleScript can't reset Table to default

The point of this module is to have a Dictionary, every time a player joins, a Key with the player’s name is created, showing information about the player’s character (stuff like if it’s stunned, on cooldown, etc.)

So i was testing it out and it seems to work fine, whenever i change a or add a value from another script, it registers and all scripts that require this module can read it. Only problem is, i want the values to reset to default every time the CharacterAdded function is called(when he respawns).

local Players = game:GetService("Players")

local DefaultCharacterTable = {Cooldowns = {}, Stuns = {}, SpeedMultipliers = {}, Confirmations = {}}

local CharacterTables = {}

-- The problem is isolated to this function here, everything else is just for context
local CharacterAdded = function(Character)
	
	-- Checks what the values of the table were before death 
	-- it is supposed to have a Cooldown
	-- (Another script adds the Cooldown, then kills the character)
	print(CharacterTables[Character.Name])
	CharacterTables[Character.Name] = DefaultCharacterTable
	-- Checks afterwards if the Table is back to default as it should be
	print(CharacterTables[Character.Name])
	
end

local PlayerAdded = function(Player)
	 
	CharacterTables[Player.Name] = DefaultCharacterTable
	Player.CharacterAdded:Connect(CharacterAdded)
	
end

local PlayerRemoved = function(Player)
	
	if CharacterTables[Player.Name] then
		
		CharacterTables[Player.Name] = nil
		
	end
	
end

-- In case a player has already joined before this point
for _, player in ipairs(Players:GetPlayers()) do
	task.spawn(PlayerAdded, player)
end

Players.PlayerAdded:Connect(PlayerAdded)

Players.PlayerRemoving:Connect(PlayerAdded)


local CharacterDictionary = {}

CharacterDictionary.GetCharacterTables = function()
	
	return CharacterTables
	
end

return CharacterDictionary

After the character dies, the script prints out:


   05:04:48.971   ▼  {
                    ["Cooldowns"] =  ▼  {
                       ["RandomCooldown"] = true
                    },
                    ["Stuns"] = {}
                 }
  05:04:48.971   ▼  {
                    ["Cooldowns"] =  ▼  {
                       ["RandomCooldown"] = true
                    },
                    ["Stuns"] = {}
                 }

Meaning that the other script managed to add a cooldown, but the module script didn’t manage to set everything to default afterwards.

Hey there,

the issue is that whenever you’re “resetting” the value indexed to the key, you’re not resetting it but referencing to the table DefaultCharacterTable.

This means that all the keys are pointing to that table and there are no unique ones.

There’s 2 fixes for that.

Simple one:

And a more advanced an unnecessary one would be deep copying the DefaultCharacterTable.

Hope this helps.

1 Like

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