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.
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.
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.