How would I check if a variable has changed?

I’m not sure if this is possible, but how would I check if a variable like 1 changes instead of having to use an infinite loop.

local var = 1

local function onChange()
   -- blah blah blah
end
-- how to run onChange when var changes
2 Likes

Just do:

if var == 1 then
       print("Var variable hasn't changed!")
else
        -- var variable has changed..
end

There are multiple ways to do it.

  1. Use a Value Instance and use the Changed or PropertyChanged event to do it.
  2. Use the __newindex metamethod in a metatable to do it.
    __newindex(table, index, value)
  3. Just use another function to change the value and at the same time trigger the onChanged instead
local var = 1

local function onChange()
   -- blah blah blah
end

local function changeVar(newVar)
    onChange()
    var = newVar
end

changeVar(5)
4 Likes

Usually you want to add a line after the variable has changed(operation) instead of relying on events. This is however subjective to what sort of scripting architecture you’re looking for.

13 Likes

Yeah, I want to detect when It changes. I don’t want to detect what it changes to, I don’t wanna use an infinite loop to keep checking it

You can use GetPropertyChangedSignal(The value you need) if you are using a value object and property.

2 Likes

Yeah I’ll probably just create a Value object and use that. Thanks for your help

GetPropertyChangedSignal actually works for any property of any object, like a Part’s transparency.

Just some additional info that may help :slight_smile:

3 Likes

I know. I’ll probably just use Value.Changed tho, thanks!

2 Likes