Both of those will result in a syntax error. Syntax errors occur when you don't follow the writing consistency (or grammar) of the language.
New index
Assigning a new index to a table isn't unlike creating a new variable... for a table. The syntax remains the same, all you're doing is specifying what index of the table you'd like to overwrite. For example...
local t = {}
t[1] = "Hello"
t[2] = "world"
The code above inserts Hello as the first element in the array, and world as the second. This syntax is no different for dictionaries. Remember, dictionaries and arrays are still both tables. No rules change, they're just different formats. Keeping this in mind, let's try adding another table (which happens to be in dictionary format) to our array...
local t = {}
local dictionary = {x = 1, y = 2, z = 3}
t[1] = dictionary
print( t[1].x )
The code above now assigned the first position in the table to reference the dictionary object we created. This however, is for a specific position in the table. Let's say we always wanted to append the dictionary to the end of the array...
local t = {}
local dictionary = {x = 1, y = 2, z = 3}
t[#t+1] = dictionary
print(t[1].x, t[#t].x)
Notice how both indices of the table above yield 1. This is because the length of the array (the #t operation) is one, after appending our dictionary. The table.remove and table.insert functions aren't very necessary unless you're using them with their optional arguments (certain positions in the table other than the very end). This is because these two examples are exactly the same...
local t = {}
table.insert(t, "Hello")
t[#t+1] = "Hello"
Likewise with table.remove...
local t = {"Hello"}
table.remove(t, #t)
t[#t] = nil
Again, both examples above do the same thing. The only difference is that table.remove actually returns the value it's removing, which can also be very useful.
You should also know that you should only be using the table functions on a sorted array. They will not work on tables in dictionary format, because dictionaries do not have numerically sorted indices. Same goes with getting the length of a table using #, this will only work for arrays for the same reason.
Hope this helped, let me know if you have any questions. I tried to make this as informative as possible while staying on topic, hope I did a good job.
1 comment
Thanks for the insightful answer