Listen when property changed ( OOP )

Hello !

I was trying to be able to listen when a property is changed in a custom oop class but I just don’t seem to be able to understand how the previous post did it neither the official lua documentation. I says to use .__newindex but either I get an error, either it detect changes but methods don’t work and also the other way around.

Could somebody help explain it to me because I’ve spend far too much time on this already.

Thanks!

Article 1 : How do I know when a property is changed? (OOP)
Article 2 : Is it possible to detect when an attribute for a self-made class changes?

Show us your solution and then we might be able to help. :slight_smile:

local Class = {}

Class.Value = 1

function Class:PrintValue(Name)
	print(self[Name])
end

local _t = Class
local Proxy = {}
local Meta = {}

local ChangedEvent = Instance.new('BindableEvent')

--Meta.__index = Class
Meta.__newindex = function(t, i, v)
	print(v)
	_t[i] = v
	ChangedEvent:Fire(i, v)
end

Proxy.Changed = ChangedEvent.Event

setmetatable(Proxy, Meta)

return Class

I tried a lot of things but this is the last attempt that I got. This is not how you normally do classes but in my case I only want it to be a requestable module with general properties and functions available to every script.

local Class = {}
local Proxy = {}
local Meta = {}

Proxy.Value = 1

function Proxy:PrintValue(Name)
	print(self[Name])
end

local ChangedEvent = Instance.new('BindableEvent')

Meta.__index = Proxy
Meta.__newindex = function(t, i, v)
	print(v)
	Proxy[i] = v
	ChangedEvent:Fire(i, v)
end

Proxy.Changed = ChangedEvent.Event

setmetatable(Class, Meta)

return Class

This should work.
I believe it could be done even with just Meta and Proxy, since Proxy is the data storage and Meta is the accessor.
Important to remember that if your Proxy table contains different fields other than Value it will still call Changed for the field which was updated.