gpt4 book ai didi

lua - table.remove 的特殊情况

转载 作者:行者123 更新时间:2023-12-05 00:13:24 25 4
gpt4 key购买 nike

The reference manualtable.remove说:

table.remove (list [, pos])

Removes from list the element at position pos, returning the value of the removed element. When pos is an integer between 1 and #list, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list] and erases element list[#list]; The index pos can also be 0 when #list is 0, or #list + 1; in those cases, the function erases the element list[pos].


最后两个特殊情况 pos0#list + 1我感兴趣。
pos 的示例代码正在 0 :
local t1 = {[0] = 'foo'}
table.remove(t1, 0)
在这种情况下,元素 t1[0]已移除。
pos 的示例代码正在 #list + 1 :
local t2 = {'foo', 'bar', 'baz'}
table.remove(t2, #t2 + 1)
在这种情况下,除了语句不会引发错误之外,没有任何变化。

我的理解正确吗?这两个特殊情况在实践中何时有用?
我还注意到这两种情况是从 Lua 5.2 开始添加的

最佳答案

表通过匹配键和值来工作。默认情况下,键从 1 开始并转到#list。所有未定义的键的值都是 nil。

t = {}
print(t[1])
>>nil

所以你的代码只是在 #t + 1 中返回 nil

在实践中,表格通常从 1 开始。但是在某些应用程序中,例如图形,从 0 开始可能更有意义。

关于lua - table.remove 的特殊情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com