为什么在Lua中,t:insert(9)
不能正常工作?
(我想将值为9的元素添加到表的末尾)
t = {1,2,3}
table.insert(t, 9) -- works (appends 9 to end of table t)
t:insert(9) -- does NOT work
我认为一般情况下,a.f(a,x)
在Lua中等同于a:f(x)
虽然 a:f(x)
只是 a.f(a,x)
的语法糖,但你的代码并不是这种情况。反向思考一下:
你尝试调用的函数是 t:insert(9)
那么根据你所说的语法规则应该是 t.insert(t, 9)
但实际工作的函数调用是 table.insert(t, 9)
看到最后两个不一样了吗?因此,答案是 insert() 不是包含在 t
中的函数,而是在 "table" 中。
由于table
方法未与t
相关联,因此您需要通过table.insert
语法直接调用它们,或在t
上定义metatable为table
,例如:
> t = {1,2,3}
> setmetatable(t, {__index=table})
> t:insert(9)
> print (t[4])
9
t -> something else -> table
,它会级联传递,但我自己还没有测试过。 - BMitch您正在调用表中名为“insert”的条目,然而,在表t中并没有这样的条目。如果您想让它工作,您可以将插入条目设置为table.insert。
t = {insert = table.insert, 1, 2, 3}
t:insert(9)
print(t[4]) -- 9, as you'd expect
table.insert(t, v)
吗? - frooyo