How to check when a value updated in a table?

I wanted to link a function to whenever the value of a index updated, I have tried to use metatables but they only detect when new ones are added. So for example:

function deathCheck()

end

local tab = {HP = 100,MHP = 100}

--When HP updated, deathCheck() is called 

you could do this

tab.HP = 50
deathCheck()

just call the function after you change it

1 Like

so are there no ways to detect a change?

nothing automatic that I currently know of

You can’t check vanilla table changes, the only way is through __newindex metamethod which only fires if they current value is nil which is another problem.

One way to fix this is to have one table and a proxy table. The proxy table will hold all the contents and we will use metatables to connect the main to the proxy. The main table will be empty so __newindex and __index will fire

-- containers
local main = {}
local proxy = {}
local meta = {}

-- create an event
local ChangedEvent = Instance.new('BindableEvent')

-- properties
proxy.HP = 100 -- set values

proxy.Changed = ChangedEvent.Event -- so they can do main.Changed:Connect(fun.. etc

-- setting metatable behaviour
meta.__index = proxy
meta.__newindex = function(t, i, v)
  if t[i] ~= v then
    proxy[i] = v
    ChangedEvent:Fire(i, v) -- fire the event with the property changed as the first paramter and the new variable as the second
  end
end

return setmetatable(main, meta)

A lot more confusing than needed but can be useful

local main = require() -- whereever the module was placed

main.Changed:Connect(function(property, new_value)
  print(property..' has been changed to'..tostring(new_value)..'!')
end)

main.HP = 70 -- HP has been changed to 70!

But this is the only way I know of how to detect changes well.

7 Likes

you could do this

local tab = {
    HP = 100,
    MHP = 100
}

function deathCheck()

end

function SetValue(Index, Value)
    tab[Index] = Value
    deathCheck()
end

SetValue("HP", 50)
SetValue("MHP", 200)

you can use the function SetValue

1 Like