Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 5 years ago

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)

2
You should never sacrifice readability. The difference is probably very small. User#19524 175 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago

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.

Ad

Answer this question