Questions about table.insert

1: When using table.insert, if i have an existing value at 1, and insert a new value at 1, is the old value moved to 2, or is it overwritten?

2: What are advantages to using table.insert as apposed to table[index] = value?

  1. It’s placed at 1 and everything at 1 and up is moved up by 1.
  2. You can place items inside a table without having to worry about indexes. Ex; table.insert(Table, "a") will place the string “a” at the end of the table.
3 Likes

You can use table[#table + 1] = value to get the default result of table.insert. #table gets the length of the table, so if the table has 1 value in it, it becomes table[1 + 1] = value, placing it at the end of the table. This is the preferred way of putting values into arrays. The only advantage table.insert has is if you use the optional position parameter so that it moves and relocates values 1 index higher if needed.

1 Like

Fun little thing, you can set the index metatable of your arrays to table to get some object-oriented stuff going around:

local array = {}
setmetatable(array, {__index = table})

-- example usage
array:insert("Hello")
array:insert("World!")

array:foreach(print) --> "1 Hello" / "2 World!"
7 Likes

table.insert (table, [pos,] value)

I’m sure this is the way to go.
table - The table’s name
{pos} - A number that signifies which place the variable should go in the table
value - The variable.

If the pos isn’t mentioned it will go to the end by default. It won’t override stuff if you pick a pos that is already taken. It will simply move everything down one.

This is a brief way of explaining it. If you want it more in detail. I suggest reading this page:

https://www.lua.org/manual/5.1/manual.html#pdf-table.insert

-hope this helped

1 Like