How do I append to a table in Lua

LuaLua Table

Lua Problem Overview


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?

Lua Solutions


Solution 1 - Lua

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")

Solution 2 - Lua

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.

Solution 3 - Lua

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondrewishView Question on Stackoverflow
Solution 1 - LuarsethcView Answer on Stackoverflow
Solution 2 - LualhfView Answer on Stackoverflow
Solution 3 - LuaAStopherView Answer on Stackoverflow