Search code examples
luainsertlua-table

What does "table:insert()" do?


I understand what colon syntax does. I know what table.insert(list, value) does. I'm also aware that I cannot create my own table t={} and insert a value to it with t:insert(value). But when I do table:insert(value) it inserts the value to table which is supposed to a type, right? The worst thing is that I can read this value by calling table[1]. What did I just do? How did I insert a value into a type? Why regular tables don't support colon syntax? I tried to Google it up but I just get information about tables in general, not about this particular case.


Solution

  • What did I just do?

    The syntax A:B(C) is nearly equivalent to A.B(A, C), you can check my another answer: link.

    So table:insert(value) just means table.insert(table, value), it inserts value into the table table (have nothing to do with t).

    How did I insert a value into a type?

    table.insert(t, value)
    

    Why regular tables don't support colon syntax?

    Because t:insert(value) means t.insert(t, value), but this regular table doesn't have the key insert.

    You can solve this by adding the function to the table

    t.insert = table.insert
    

    Or using a metatable

    setmetatable(t, {__index = {insert = table.insert}})