10

Why isn't t:insert(9) working in Lua?
(I want to append a value of 9 to the end of the table)

t = {1,2,3}
table.insert(t, 9)  -- works (appends 9 to end of table t)
t:insert(9)         -- does NOT work

I thought in general

a.f(a,x) is equalivant to a:f(x) in Lua

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
frooyo
  • 1,863
  • 3
  • 19
  • 21

3 Answers3

16

While it's true that a:f(x) is simply syntactic sugar for a.f(a,x) that second syntax is not what you have there. Think it through backwards:

The function call you tried is t:insert(9)

So the syntax rule you stated would be t.insert(t, 9)

But the working function call is table.insert(t, 9)

See how the last two aren't the same? So the answer to your question is that insert() isn't a function contained in t, it's in "table".

frooyo
  • 1,863
  • 3
  • 19
  • 21
jhocking
  • 5,527
  • 1
  • 24
  • 38
11

Since the table methods haven't been associated with t, you either have to call them directly through the table.insert syntax, or define the metatable on t to be table, e.g.:

> t = {1,2,3}
> setmetatable(t, {__index=table})
> t:insert(9)
> print (t[4])
9
BMitch
  • 231,797
  • 42
  • 475
  • 450
  • Setting the metatable to "table" is a clever solution I hadn't thought of, but the downside is that you can't set the metatable to something else. – jhocking May 25 '11 at 17:51
  • 1
    I think you could still set the metatable like: `t -> something else -> table` and it would cascade through, but I haven't tested it myself. – BMitch May 25 '11 at 19:22
3

You're trying to call an entry in your table called insert, however, in table t, there is none. If you want it to work, what you could do is to set the insert entry to table.insert

t = {insert = table.insert, 1, 2, 3}
t:insert(9)
print(t[4]) -- 9, as you'd expect
Bronzdragon
  • 345
  • 3
  • 13