How to detect when value in dictionary changed

I have a module script with a dictionary in it. How would I detect when a value in the dictionary is changed?

Please help

1 Like

You can’t really do that.
What you can do is trigger some function when you make those changes.

Why do you need to know when it changes?

You cannot detect changes in any values, such as, booleans, strings, number. When they’re stored in a variable which not able to detect any changes that happens to this variable.
Using loops to use if then statement will yield your next code.

You can use instances that able to store your value into one object (attributes works too) and check if their Detected event has been fired, such as, ObjectValue, NumberValue, StringValue, Color3Value and more.

When Detected event is fired, you can run any code you want in your script.

I’m doing some settings and I want the user to have a ‘chat enabled’ option. When they toggle it on/off, it toggles the chat accordingly.

You can use metamethods like __newindex

1 Like

You can achieve this with metatables.
With a proxy table, you can intercept any __newindex (changing of value) and do what you want with it.

Here’s a very basic example I just made, though if you want to access the actual table, you would have to do local actualTable = getmetatable(proxyTable).__index.

local function addProxy(targetTable, onChanged)
	return setmetatable({}, {__index = targetTable, __newindex = function(self, index, value) -- // __newindex is fired when a new value is added to a table
		targetTable[index] = value

		task.spawn(onChanged, index, value) -- // run the onChanged function on a new thread
	end})
end

local thisTable = addProxy({
	Value = 'lol',	
}, function(index, value)
	print('table changed '..tostring(index)..' to "'..tostring(value)..'"')
end)

thisTable.Value = 'new value or something'
thisTable.Value = 'an even newer value'

print(thisTable.Value)
2 Likes

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