Is it possible to check like .Changed function of a variable of module?

Hello!
I was wondering if it’s possible to check change function of a variable in a script, if it’s possible then how will i do it?

By default, no, you can’t listen for a standard variable to change. But with a bit of abstraction, you could use a BindableEvent and use setter/getter methods:

local MyModule = {}

-- Private variable, only accessible by this module internally:
local myNumber = 0

-- Create the event:
local changed = Instance.new("BindableEvent")

-- Expose the event on the module:
MyModule.NumberChanged = changed.Event

-- Setter:
function MyModule:SetNumber(n)
   if (n ~= myNumber) then
      myNumber = n
      changed:Fire(n)
   end
end

-- Getter:
function MyModule:GetNumber()
   return n
end

return MyModule
-- Test it:
local myModule = require(somewhere.MyModule)

myModule.Changed:Connect(function(num)
   print("Number changed:", num)
end)

for i = 1, 10 do
   myModule:SetNumber(i)
end

If you want to get fancier, you could use metatables with __index and __setindex to avoid having the setters and getters.

6 Likes