122

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?

2
  • 12
    The entire documentation is available at lua.org/manual/5.2 Commented Dec 11, 2014 at 23:14
  • 7
    oh that's really helpful. google kept pointing me towards lua.org/pil/2.5.html which is basically useless. Commented Dec 11, 2014 at 23:15

3 Answers 3

188

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")
Sign up to request clarification or add additional context in comments.

2 Comments

@rsethc 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.
I think it would be helpful to point out that the second parameter, which specifies the insert position, is optional. The function itself does a good job, but the naming is unfortunately not entirely obvious.
75
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.

2 Comments

It's slightly fast than table.insert.
It's worth noting that if the __shl function returns self, pushed could be chained, e.g. _= foo << "bar" << "baz"
20

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.

1 Comment

So a_table:insert("b")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.