table.insert(t, i) 和 t[#t+1] = i 有什么区别? [英] What's the difference between table.insert(t, i) and t[#t+1] = i?
问题描述
在 Lua 中,似乎有两种方法可以将元素附加到数组中:
In Lua, there seem to be two ways of appending an element to an array:
table.insert(t, i)
和
t[#t+1] = i
我应该使用哪个,为什么?
Which should I use, and why?
推荐答案
使用哪个取决于偏好和环境:由于 #
长度运算符是在 5.1 版中引入的,t[#t+1] = i
在 Lua 5.0 中不起作用,而 table.insert
从 5.0 开始就已经存在,并且可以在两者中使用.另一方面,t[#t+1] = i
只使用语言级别的运算符,而 table.insert
涉及一个函数(它有少量的开销查找和调用并依赖于环境中的table
模块).
Which to use is a matter of preference and circumstance: as the #
length operator was introduced in version 5.1, t[#t+1] = i
will not work in Lua 5.0, whereas table.insert
has been present since 5.0 and will work in both. On the other hand, t[#t+1] = i
uses exclusively language-level operators, wheras table.insert
involves a function (which has a slight amount of overhead to look up and call and depends on the table
module in the environment).
在Lua编程的第二版中(面向Lua 5.0的第一版的更新),Roberto Ierusalimschy(Lua 的设计者)表示他更喜欢 t[#t+1] = i
,因为它更显眼.
In the second edition of Programming in Lua (an update of the Lua 5.0-oriented first edition), Roberto Ierusalimschy (the designer of Lua) states that he prefers t[#t+1] = i
, as it's more visible.
此外,根据您的用例,答案可能是都不是".请参阅有关长度运算符行为的手册:
Also, depending on your use case, the answer may be "neither". See the manual entry on the behavior of the length operator:
如果数组有洞"(即其他非 nil 值之间的 nil 值),那么 #t 可以是任何直接在 nil 值之前的索引(也就是说,它可以考虑任何这样的 nil 值作为数组的结尾).
If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).
因此,如果您正在处理有孔的数组,请使用其中任何一个 (table.insert
使用长度运算符) 可能会将您的值附加"到数组中比您想要的更低的索引.在这种情况下如何定义数组的大小取决于您,并且同样取决于偏好和环境:您可以使用 table.maxn
(在 5.2 中消失但编写起来很简单),您可以在表中保留一个 n
字段并在必要时更新它,您可以将表包装在元表中,或者您可以使用另一种更适合您情况的解决方案(在循环中,一个 循环外作用域中的局部 tsize
通常就足够了).
As such, if you're dealing with an array with holes, using either one (table.insert
uses the length operator) may "append" your value to a lower index in the array than you want. How you define the size of your array in this scenario is up to you, and, again, depends on preference and circumstance: you can use table.maxn
(disappearing in 5.2 but trivial to write), you can keep an n
field in the table and update it when necessary, you can wrap the table in a metatable, or you could use another solution that better fits your situation (in a loop, a local tsize
in the scope immediately outside the loop will often suffice).
这篇关于table.insert(t, i) 和 t[#t+1] = i 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!