ModuleScript table changing

I’m trying to store the players’ keybinds and settings in a ModuleScript, and change them when the player does. It works great, except for when I want to reset to defaults.

settingList.Settings = {
	keybinds = {
		["OpenGameplayMenu"] = Enum.KeyCode.F,
		["Interact"] = Enum.KeyCode.E,
		["OpenHUD"] = Enum.KeyCode.Q,
		["OpenBase"] = Enum.KeyCode.C,
		["OpenDailyMissions"] = Enum.KeyCode.T
	},
	RememberTab = false,
	UIScale = 100,
	LODThreshold = 500,
	LODPolling = 1.5,
	NotifTime = 3,
	AudioMute = false,
	MusicMute = false,
	MusicVolume = 100,
	FxVolume = 100,
	UiVolume = 100
}

local defaults = settingsList.Settings

When I reset to default, the ModuleScript basically just goes through and sets settingsList.Settings to whatever defaults is. defaults is supposed to cache whatever settingsList.Settings is as soon as the script is run.

However, whatever is stored in defaults changes as settingsList.Settings does, so it doesn’t reset to default at all. I’ve tried this setup for caching the default settings:

local Defaults = {}
for i,v in pairs(settingList.Settings) do
	Defaults[i] = v
end

This works better, because most things do actually reset to the default. But the keybinds table stays the same. I don’t really understand what’s happening here.

I believe the keybinds stay the same as they’re in a separate table, and in a loop it won’t go to the descendants unless you make it like that.

I’d recommend putting in a check to see if Defaults[i] is a table, and then doing another loop for that.

I did that, but keybinds still changes. Another thing I did was this:

local Defaults = {
	keybinds = {
		["OpenGameplayMenu"] = Enum.KeyCode.F,
		["Interact"] = Enum.KeyCode.E,
		["OpenHUD"] = Enum.KeyCode.Q,
		["OpenBase"] = Enum.KeyCode.C,
		["OpenDailyMissions"] = Enum.KeyCode.T
	},
	RememberTab = false,
	UIScale = 100,
	LODThreshold = 500,
	LODPolling = 1.5,
	NotifTime = 3,
	AudioMute = false,
	MusicMute = false,
	MusicVolume = 100,
	FxVolume = 100,
	UiVolume = 100
}

--local Defaults = settingList.Settings--require(script.Defaults)
settingList.Settings = Defaults

Where I store what I want the defaults to be in a table, then set the players’ actual keybinds to whatever that table is. When I reset to default, nothing changes. The Defaults table changes somehow. I never reference the Defaults table except to change settingList.Settings to what Defaults is.

Tables are mutable objects. That means when you went around and put the table of keybinds in the list of defaults, it didn’t create a copy of the table, but a reference to it. That means every time the user changes one of the keybinds in that table the table of keybinds in the defaults table change as well. Instead, create a copy of that table.

1 Like

I never knew that before. It works perfectly, thanks