Lua - table.insert 不起作用
为什么 t:insert(9)
不能在 Lua 中工作?
(我想将值 9 附加到表格末尾)
t = {1,2,3}
table.insert(t, 9) -- works (appends 9 to end of table t)
t:insert(9) -- does NOT work
我认为一般来说
af(a,x)
等于 a:f(x)
卢阿
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然
a:f(x)
确实只是af(a,x)
的语法糖,但第二种语法并不是您所拥有的。向后思考:您尝试的函数调用是
t:insert(9)
所以您所说的语法规则将是
t.insert(t, 9)
但工作函数调用是
table.insert(t, 9)
看看最后两个不一样吗?所以你的问题的答案是 insert() 不是
t
中包含的函数,它位于“table”中。While it's true that
a:f(x)
is simply syntactic sugar fora.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".由于
table
方法尚未与t
关联,因此您必须通过table.insert
语法直接调用它们,或者定义t
上的元表为table
,例如:Since the
table
methods haven't been associated witht
, you either have to call them directly through thetable.insert
syntax, or define the metatable ont
to betable
, e.g.:您试图调用表中名为 insert 的条目,但是在表 t 中没有任何条目。如果你想让它工作,你可以做的是将插入条目设置为 table.insert
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