I’m not exactly sure how to call them, I was thinking of saying “inserting” and “indexing”, but i dont think thats correct, let me know tho.
However what would be the difference between the two?
t = {} -- table
-- Example 1:
table.insert(t, 1) -- inserts item to table
print(table.find(t, 1)) -- prints if index was found ( 1 )
-- Example 2:
t[#t+1] = 1 -- Adds index by number of item's in a table
print(table.find(t, 1)) -- prints if index was found ( 1 )
The only difference I can think of might be their speed, is that all tho?
I believe table.insert is faster and that’s about it, I’ve only ever used example 2 for inserting functions into a table that I need to disconnect later as it was just easier to read.
there isnt any difference except as the others say speed. but i am sure that the speed diffrence isnt THAT MUCH also t[#t+1] can sometimes be easier to read in some cases like
local yourmother = {}
for x = 1, 10 do
yourmother[x] = {}
for z = 1, 10 do
yourmother[x][z] = {}
end
end
local yourmother = {}
for x = 1, 10 do
table.insert(yourmother,{})
for z = 1, 10 do
table.insert(yourmother[x],z) -- looks weird right and can be hard to understand.
end
end
local Damn = {}
if Damn["Yeah"] == nil then
table.insert(Damn, "Yeah")
end
Damn[#Damn] = "Yeah"
for _,v in Damn do
print(v.. " damnation "..v)
end
local Yeah = table.clone(Damn)
Yeah = {}
if Yeah["Damn"] == nil then
table.insert(Yeah, "Damn")
end
Yeah[#Yeah] = "Damn"
for _ ,v in Yeah do
print(v.." yeah "..v)
end
Well I mean to be fair, the second option does seem better but again syntax wise table insert is easier to read.
AFAIK the reason t[#t+1] = v was ever a thing was because table.insert was slower than setting your indices in the table in the past. All the standard libraries have received up to significant internal performance improvements ever since Luau so a lot of developers have gone back to just using table.insert. For readability’s sake, even prior to Luau, I’ve always preferred using table.insert to be clear that I’m working with arrays and am adding an element to one.
BTW: clickbaity title. Maybe should explain a bit more, like “What’s the difference between these two ways of table inserts?” or something.