How do I append to a table in Lua
Asked Answered
W

3

114

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?

Weekday answered 11/12, 2014 at 23:10 Comment(2)
The entire documentation is available at lua.org/manual/5.2Inappetence
oh that's really helpful. google kept pointing me towards lua.org/pil/2.5.html which is basically useless.Weekday
I
177

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")
Inappetence answered 11/12, 2014 at 23:13 Comment(2)
Exactly. You don't need the semicolons either, but you can have em if you want to.Inappetence
@Inappetence Two 'duplicate' answers were bound to be posted at the same moment sometime in Stack Overflow's history (and I bet we won't be the last to, either). To be fair I did add some information about memory/time savings.Hexad
F
72
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.

Fallfish answered 11/12, 2014 at 23:14 Comment(2)
It's slightly fast than table.insert.Abrasion
It's worth noting that if the __shl function returns self, pushed could be chained, e.g. _= foo << "bar" << "baz"Gaberones
H
17

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.

Hexad answered 11/12, 2014 at 23:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.