Is it possible to detect when an attribute for a self-made class changes?

I know of the changed event, but say that I had a self-made class as follows:

local Inventory = {}
Inventory.__index = Inventory

function Inventory.new()
        local inventory = {}
        setmetatable(inventory, Inventory)

        inventory.coins = 10

        return inventory
end

Is it possible to bind a function to fire when inventory.coins has been changed?

local Inventory = {}
Inventory.__index = Inventory

function Inventory.new()
        local inventory = {}
        setmetatable(inventory, Inventory)

        inventory.coins = 10
        inventory.coins.Changed:Connect(inventory.coinsChanged)

        return inventory
end

function Inventory:coinsChanged()

end

It might be a bit weird to do so but yea you can using __newindex and BindableEvents

local Inventory = {}
local proxy = {} -- im using proxy tables otherwise __newindex won't fire
local meta = {}

local ChangedEvent = Instance.new('BindableEvent')

meta.__index = Inventory
meta.__newindex = function(t, i, v)
  proxy[i] = v
  ChangedEvent:Fire(i, v)
end

proxy.Changed = ChangedEvent.Event

setmetatable(Inventory, meta)

return Inventory

somewhere else

Inventory = require(something)

Inventory.Changed:Connect(function(property, new_value)
  print(property)
  print(new_value)
end)

Inventory.Coins = 10 
-- prints
-- Coins
-- 10

Inventory.x = true
-- prints
-- x
-- true
1 Like