Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

is it possibe to check if a new value was added to a table or dictionary?

For example:

t = {}
table.insert(t,1,"A") 
t["hi"] = "a"

Is it possible to execute a function whenever they are called? I tried with metatables but looks like table.insert and metatables dont go well together. Please help.

1 answer

According to Nifim on Stack Overflow, you can run this code

local function listener(k,v)
  print( "new entry added: \n\tKey = " .. k .. "\n\tValue = " .. v)
end

local metaTable

do
  local protectedTable = {}
  metaTable = {
    __index = function (t,k)
      return protectedTable[k]
    end,
    __newindex = function (t,k,v)
      protectedTable[k] = v   -- update original table
      listener(k,v)
    end
  }
end

local t = setmetatable({},metaTable)

t.text = "Hello!"
print(t.text)

More information here.

This discussion is preserved as it was. New answers, comments, and votes are closed.