Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Which is better, table.insert() or tbl[#tbl + 1] = val?

##Readability

I find table.insert to look much more cleaner than tbl[#tbl + 1] = val. You could see that you are inserting a value with table.insert rather than tbl[#tbl +1] = val

local tbl = {}

table.insert(tbl,5) -- Optional second argument: the position it is at; defaults to #tbl + 1
tbl[#tbl +1] = 5 -- Looks ugly in general. I would prefer table.insert for readability

##Speed

tbl[#tbl +1] = val is actually faster than table.insert(). This is probably because table.insert has some internal things going on

##Question

So, which should I use, table.insert or tbl[#tbl + 1] (I have also noticed in some of roblox's scripts that they have been using table.insert instead of the optimal way of tbl[#tbl + 1] = val)

1 comment

2

You should never sacrifice readability. The difference is probably very small.

1 answer

table.insert() is definitely more practical, and much faster. It is also a vanilla Lua function. tbl[#tbl + 1] = val is very bad practice as it is mostly hard to read, though there is no difference exactly besides the fact that it might just take a little longer.

This discussion is preserved as it was. New answers, comments, and votes are closed.