Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `table.insert` work with custom tables in Lua

Tags:

lua

lua-table

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!!
like image 634
Karim Tarabishy Avatar asked Jun 28 '13 16:06

Karim Tarabishy


1 Answers

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.

like image 185
deepspace Avatar answered Nov 15 '22 08:11

deepspace