Questions on metatables and problem with _newindex not invoking

Hello, so to start, a couple questions I would like to ask on metatables:

  1. If for example, I set a metatable as follows: local t = {table, metatable} (treating the metatable and table variables as already defined), if I would like to loop through the table, should I call the table or should I call t?

  2. Should I use (table)[index] = value or table.insert to invoke _newindex?

Now, onto the problem:

local t = setmetatable(table,{
    _newindex = function(t, i, v)
	    print("New Index")
        rawset(table, i, v)

local function addtotable()
    print("Event Fired")
    t[#t + 1] = true


When SomeEvent Event is fired, print("Event Fired") does print however, _newindex is not invoked as print("New Index") does not print. Is there something wrong with the code that I have written above?

1 Like

The issue i believe is that you forgot to put two underscores instead of one, it should be __newindex not _newindex.

  1. I’m guessing you are talking about iterating over table, so in that case, it wouldn’t matter whether you use table or t. the table returned from setmetatable is the table you are trying to give a metatable to. So essentially t is table.

  2. table.insert uses rawset (IIRC), it will never fire __newindex


It does (good to know that considering I’ve never heard of that!)


@Jaycbee05 Thanks for the clarification, this really clears everything up. I just learnt about metatables and I guess I couldn’t differentiate between the single and double underscores when I was reading it in the Developer Hub.

I shouldn’t have been so surprised to hear that t is table (but I was), why didn’t I think of that!

@vtaetwrjxvdpgwjqkfzw I’m getting mixed messages but I’ll give both a try. Thanks!