table.insert(t,i)和t [#t + 1] = i有什么区别?

编程入门 行业动态 更新时间:2024-10-27 14:21:09
本文介绍了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有什么区别?

本文发布于:2023-07-29 09:03:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239326.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   table   insert

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!