How `table.insert` works with user tables in Lua

I wonder how table.insert works in lua ?!

I ask about this because I tried to use it in a user table with the __newindex metamethod but it doesn't seem to be that way. Is there a way to get my custom table functions to work with table.insert ?!

From my humble knowledge of the language, I would say that it uses something like rawset or something, maybe I don’t know.

Sample I worked on:

 do tabl = {1,2,3} local _tabl = tabl tabl = {} local mt = { __newindex = function(t,k,v) print"changing" ;_tabl[k] = v end, __index = _tabl} setmetatable(tabl,mt) end tabl[4] = 4; --prints "changing" table.insert(tabl,5) -- prints nothing!! 
+4
source share
2 answers

There is no such metamethod, table.insert simply inserts a new value into the specified table.

 local myTable = {} table.insert(myTable, "somestring") -- so now myTable has one value, myTable = { "somestring" } 

It works like:

 local myTable = {} myTable[#myTable + 1] = "somestring" 

__ newindex metamethod only affects the assignment operator "=", table.insert is just a separate function, not related to meta tags, you can change the behavior of this function if you want:

 _tableinsert = table.insert function table.insert(t, v) -- here your actions, before real function will be used _tableinsert(t, v) end 

I think it would be possible to create your own __tableinsert metamethod this way.

+5
source

table.insert really uses rawset. See lua 5.1 Source here .

As indicated, if you complete the task yourself, you should be able to get the right behavior.

+3
source

Source: https://habr.com/ru/post/1488725/


All Articles