5

I wonder how does table.insert work in lua?!

I am asking this because I have tried to use it on a custom table with __newindex metamethod but it seems not to call it. Is there a way to make my custom table functionality to work with table.insert?!

From my humble knowledge about the language I would say it uses something like rawset or something maybe I donno.

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!!
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Karim Tarabishy
  • 1,223
  • 1
  • 13
  • 25

2 Answers2

5

There's no such metamethod, table.insert just inserts a new value to a 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 affects only assignment operator "=", table.insert is just a separate function not related with metatables, you can modify the behaviour 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 that would be possible to make your own metamethod __tableinsert this way.

deepspace
  • 771
  • 3
  • 11
  • 25
3

table.insert does, in fact, use rawset. See the lua 5.1 source here.

As indicated if you do the assignment yourself you should be able to get the behavior you want.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148