table.insert(t,i)和t [#t + 1] = i有什么区别? [英] What's the difference between table.insert(t, i) and t[#t+1] = i?

查看:705
本文介绍了table.insert(t,i)和t [#t + 1] = i有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Lua中,似乎有两种将元素附加到数组的方法:

table.insert(t, i)

t[#t+1] = i

我应该使用哪个,为什么?

解决方案

使用哪种方法取决于您的偏好和情况:由于# length运算符是在5.1版中引入的,因此t[#t+1] = i在Lua 5.0中将不起作用,而table.insert从5.0开始就出现在这两个版本中.另一方面,t[#t+1] = i仅使用语言级别的运算符,而table.insert涉及一个函数(查找和调用的开销很小,并且取决于环境中的table模块).

在Lua中编程的第二版中(面向Lua 5.0的第一版的更新) ),Lua的设计师Roberto Ierusalimschy指出,他更喜欢t[#t+1] = i,因为它更明显.


此外,根据您的用例,答案可能是都不".请参见有关长度运算符行为的手动输入:

如果数组具有空洞"(即其他非nil值之间的nil值),则#t可以是直接在nil值之前的任何索引(即,它可以考虑任何此类nil值)作为数组的结尾).

这样,如果您要处理带有孔的数组,请使用其中一个( table.insert使用长度运算符)可能会将您的值附加"到数组中比所需的索引低的位置.在这种情况下,如何定义数组的大小取决于您自己,并且再次取决于首选项和情况:您可以使用table.maxn(在5.2中消失,但编写起来很简单),可以保留n字段在表中并在必要时对其进行更新,您可以将表包装在一个元表中,或者可以使用更适合您的情况的另一种解决方案(在循环中,循环外的作用域中的local tsize通常就足够了).

In Lua, there seem to be two ways of appending an element to an array:

table.insert(t, i)

and

t[#t+1] = i

Which should I use, and why?

解决方案

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

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:

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆