In Lua, there seem to be two ways of appending an element to an array:
table.insert(t, i)
and
t[#t+1] = i
Which should I use, and why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Which to use is a matter of preference and circumstance: as the
#length operator was introduced in version 5.1,t[#t+1] = iwill not work in Lua 5.0, whereastable.inserthas been present since 5.0 and will work in both. On the other hand,t[#t+1] = iuses exclusively language-level operators, wherastable.insertinvolves a function (which has a slight amount of overhead to look up and call and depends on thetablemodule in the environment).In the second edition of Programming in Lua (an update of the Lua 5.0-oriented first edition), Roberto Ierusalimschy (the designer of Lua) states that he prefers
t[#t+1] = i, as it’s more visible.Also, depending on your use case, the answer may be “neither”. See the manual entry on the behavior of the length operator:
As such, if you’re dealing with an array with holes, using either one (
table.insertuses the length operator) may “append” your value to a lower index in the array than you want. How you define the size of your array in this scenario is up to you, and, again, depends on preference and circumstance: you can usetable.maxn(disappearing in 5.2 but trivial to write), you can keep annfield in the table and update it when necessary, you can wrap the table in a metatable, or you could use another solution that better fits your situation (in a loop, alocal tsizein the scope immediately outside the loop will often suffice).