Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - table.insert not working

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

like image 463
frooyo Avatar asked May 25 '11 15:05

frooyo


2 Answers

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

like image 70
jhocking Avatar answered Nov 17 '22 21:11

jhocking


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
like image 11
BMitch Avatar answered Nov 17 '22 21:11

BMitch