[lua] How do I append to a table in Lua

I'm trying to figure out the equivalent of:

foo = []
foo << "bar"
foo << "baz"

I don't want to have to come up with an incrementing index. Is there an easy way to do this?

This question is related to lua lua-table

The answer is


You are looking for the insert function, found in the table section of the main library.

foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")

foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"

This works because the # operator computes the length of the list. The empty list has length 0, etc.

If you're using Lua 5.3+, then you can do almost exactly what you wanted:

foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"

Expressions are not statements in Lua and they need to be used somehow.


I'd personally make use of the table.insert function:

table.insert(a,"b");

This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.