Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading