104

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?

greatwolf
  • 20,287
  • 13
  • 71
  • 105
drewish
  • 9,042
  • 9
  • 38
  • 51
  • 9
    The entire documentation is available at http://www.lua.org/manual/5.2/ – rsethc Dec 11 '14 at 23:14
  • 5
    oh that's really helpful. google kept pointing me towards http://www.lua.org/pil/2.5.html which is basically useless. – drewish Dec 11 '14 at 23:15

3 Answers3

165

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")
rsethc
  • 2,485
  • 2
  • 17
  • 27
  • 1
    Exactly. You don't need the semicolons either, but you can have em if you want to. – rsethc Dec 11 '14 at 23:16
  • 1
    @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. – AStopher Dec 11 '14 at 23:18
69
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.

lhf
  • 70,581
  • 9
  • 108
  • 149
14

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.

AStopher
  • 4,207
  • 11
  • 50
  • 75