Detecting a change in a variable

So I have this variable inside a script and want to see how can I detect when it changes?

You cant check if a variable has changed

But there is a solution, I know you can’t change a variable automatically so

Example:

local Variable = 0

for i=1, 10 do
	Variable = i
	print("Variable has changed")
end

Hmm alright, why did you remove walter white :sob:

There is no built-in way to detect changes in variables, although you can create your own method thanks to tables but it’s not optimal and you should do what Birdiel90 suggested.

local Variables = {
   Hello = "Hi";
};

local function DetectChange(Table, VarName)
   local LastValue = Table[VarName];
   game:GetService("RunService").Stepped:Connect(function(DeltaTime)
      if Table[VarName] == LastValue then return end;
      print("Variable", VarName, "has changed");
      LastValue = Table[VarName];
   end);
end;

DetectChange(Variables, "Hello")

if the value is simple like a number or a string, why not just use NumberValue, StringValue, etc?

local numberVal = Instance.new("NumberValue")
numberVal:GetPropertyChangedSignal("Value"):Connect(function()
	print("numberVal has changed!")
end)

task.wait(2)

numberVal.Value = 3
5 Likes