#How does __newindex actually work in OOP? (WILL PAY)

15 messages · Page 1 of 1 (latest)

topaz chasm
#

I'm exploring OOP and noticing many people use __newindex to monitor property changes, but I don't understand its functioning despite reviewing Roblox documentation.
Thank you for helping me, I'll pay you with a heart full of love. KissCowboy

novel nimbus
#

__newindex is essientally just a function that fires when an new index is assigned to

#
local metatable = {}

metatable.__newindex = function(t, i, v)
    print(`t[{i}] was assigned to. v: {v}`)
end

local t = setmetatable({
    x = 1
}, metatable)

t.x = 2 -- will print, since x is being assigned to.
doSomething(t.y) -- will not print, since it's being accessed. (use __index for that.)
#

so essientally, if it exists, __newindex will only fire if you're adding something that didn't already exist to the dictionary

topaz chasm
novel nimbus
#

that's probably a better way to say it

#

uhh

topaz chasm
#

Is there any way?

novel nimbus
topaz chasm
#

like the .Changed event for instance

novel nimbus
#

__newindex = funciton(t, k, v)
    if t[k] then
      -- your code here
    end
end
#

you can use rawset/rawget to change them without firing the metamethods.