Why do people use table[index + 1] = val instead of table.insert()? And it’s not only that. People also use table[index] = nil or something like that. But why? Is it more efficient than table.insert() or table.remove()? Thanks for answering!
A little more information. If you’re confused on what I’m trying to say, this is what I mean:
for index = #myTable, 1, -1 do
myTable[index + 1] = "Hello world!"
end
local arraytable = {"goodtimetousetableinsert"}
table.insert(arraytable,"yes,goodtime")
local dictionarytable = {
[1] = "good time to use their method"
}
for index = #dictionarytable, 1, -1 do
dictionarytable[index + 1] = "yeah, good time"
end
Arrays are indexed via sequential numbers starting from 1 automatically. local dictionarytable = {[1] = "good time to use their method"}
Is the same as: local dictionarytable = {"good time to use their method"}
Note that the table.insert() requires a numerical index when you are specifying where to insert something, so it’s intended for use with arrays as bindableunderscore said. There is overlap in functionality since arrays and dicts are both lua tables. Either approach works if it does what you need.
Internally, every table has an array and hashmap portion, and so a table can be both a dictionary and an array at the same time.
local t = {}
-- insert a value into the hashmap (ie., dictionary) part of the table
t[0] = "dictionary value"
-- insert values into the array part of the etable
for i = 1, 5 do
table.insert(t, i)
end
-- this will print all values of the array-part of the table, ignoring the value at index 0.
for i, v in ipairs(t) do
print(v)
end
-- this will the value stored in the hashmap part of the table, "dictionary value".
print(t[0])
adding onto this, t[#t + 1] still inserts values into the array-part of the table in Luau. This is because the #t operation only returns the integer length of the array-part of the table, like so: