Table.insert not triggering metatable __newindex

The topic title is pretty much self explanatory.

I’ve tried to add a __len method but it didn’t help much.

Here’s my code:

local raw_table = {
	[1] = "hello",
	[2] = "hi",
	[3] = "welcome"
}

local metatable = setmetatable({},{
	__len = function()
		return #raw_table
	end,
	__index = raw_table,
	__newindex = function(_,key,value)
		warn("Fired __newindex")
		raw_table[key] = value
	end
})

metatable[#metatable+1] = "extra value 1" ---triggers __newindex
print(metatable) -- [empty]
table.insert(metatable,"extra value 2") ---does not trigger __newindex, inserted into metatable instead
print(raw_table)
print(metatable) -- {"extra value 2"}

I believe table.insert uses rawset internally which bypasses any metamethods. So unfortunately, you’ll need to use another way of inserting into table for __newindex to fire.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.