How to detect if a value is added inside a table?

I’ve already found a “solution”. but, table.insert() does not work and i can’t really find a way for table.insert() to work.

code:

local myTable = {}

local metaTable = {
  __newindex = function(table, key, value)
    print("Value inserted:", key, value)
    rawset(table, key, value) -- insert value
  end
}

setmetatable(myTable, metaTable)

doing myTable["key1"] = "value1" is not really a good way of inserting a value inside a table in my case because i will need to debug a lot just to check if i set a value of a table right.

1 Like

Explain what you are trying to do, and why. There is not enough context here to understand why inserting values to the table will not work via table.insert or any other method.

1 Like

I am just trying to detect if a value is inserted in a table just simple as that. I have no clue why table.insert() is not working though it’s probably because table.insert() asks for the size of the table (?).

Just create an event that gets fired when you add an object to the table and pass the data inserted into the table through the event. You now have an event for when data is inserted into the table that you can listen to.

table.insert(tbl, val) will not work in this situation, but tbl[#tbl + 1] = val will.

table.insert calls lua_rawseti to insert a value into a table in Luau (https://github.com/Roblox/luau/blob/61afc5e0dd5b87df87e13e938df19f6b5b2935b1/VM/src/ltablib.cpp#L162)
In Lua 5.3 and higher, table.insert calls lua_seti to do this so it will work in Lua 5.3 and higher. Luau is Lua 5.1-based.

As a result, in your case, __newindex metamethod is not called when calling table.insert.

4 Likes

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