How to detect when Variables change

I’m trying to do something like this:

local Variable = false
Variable.Changed:Connect(function()
	print('Variable has changed')
end)
wait(5)
Variable = true -- prints "Variable has changed"

I don’t want to run infinite loops or pack 100+ value objects into a folder, I searched around the forum, and other people either resorted to either of the 2 options or found no solutions.

The best alternative I can think of is to store the variables in a module and then detect when one of the variables there is changed. Here is a reference to doing it

You can do something like this but its not a variable its a table/metatable:

local callback
local container = {Variable = false}

do
	local temp = table.clone(container)
	container = {}

	local metatable = {
		__index = function(table, key)
			if key == "Changed" then
				local connection = {} 

				function connection:Connect(...)
					callback =...
				end

				return connection
			end

			return temp[key] 
		end,

		__newindex = function(table, key, value) 
			temp[key] = value
			callback(key, value)
		end
	} 

	setmetatable(container, temp) 
end

container.Changed:Connect(function(key, value)
	print(key, value) 
end)

In Laymen’s terms, what is happening here what is the script doing?

It checks if the container.Variable changed on:

I see, but when I try this in the studio it gives out an attempt to index nil with ‘Connect’ error, why? And if I were to change the Variable what would I say?

If you have just copied the code then you might need to double check for typo since I typed that on my phone.

Yes I saw that and added the comma and it gave the error, I also tried to run the edited version of the script incase there is a difference but it gave the same error:
Screen Shot 2022-07-18 at 9.50.58 AM

For what it’s worth, you shouldn’t do this unless you’re making a ModuleScript for someone else. Even then it’s debatable. You have full control over your own code and I advise making a function for this since you are reusing code.

local function changeVar(value)
    Var = value
    -- do stuff
end

you could make a loop like this

local var = false
while task.wait() do 
   if var ~= false then
     Changedfunc()
     break
   end
end

and create a different thread for the loop if you cant do loops make 1 model and add attributes to that one model for each attribute and then check if the attribute changes.

Interesting, but how safe are attributes when it comes to exploiters compared to value objects?

Both of them are the same in the way they can be exploited.

1 Like