gpt4 book ai didi

lua - table.insert 覆盖现有索引

转载 作者:行者123 更新时间:2023-12-02 04:43:20 25 4
gpt4 key购买 nike

答案:仅在序列(数组/列表)上使用 table.* 函数(仅具有从 1 开始的连续整数键的表)。它们的行为在非类似数组的表上是未定义的:它们可能会或可能不会像您预期的那样工作。


在 Lua 5.1 table.insert( t, index, value ) 中,如果索引已经存在于表中,应该向上移动值,对吗?

但它并不总是这样做:

local t = {}
table.insert( t, 4, 5 )
table.insert( t, 5, 6 )
table.insert( t, 4, 4 ) -- this erase the value 5 at key 4
-- t[4] = 4, t[5] = 6, t[6] = nil

local t = {}
table.insert( t, 1 )
table.insert( t, 2 )
table.insert( t, 3 )

table.insert( t, 6, 7 )
table.insert( t, 6, 6 ) -- this erase the value 7 at key 6
-- t[6] = 6, t[7] = nil

但是:

local t = {}
table.insert( t, 1 ) -- these two lines were added
table.insert( t, 2 )
table.insert( t, 4, 5 )
table.insert( t, 5, 6 )
table.insert( t, 4, 4 ) -- now it moves the values up
-- t[4] = 4, t[5] = 5, t[6] = 5

local t = {}
table.insert( t, 1 )
table.insert( t, 2 )
table.insert( t, 3 )
table.insert( t, 4 ) -- this line was added
table.insert( t, 6, 7 )
table.insert( t, 6, 6 ) -- now it moves the values up
-- t[6] = 6, t[7] = 7

这与在 LuaForWindows 命令行以及运行 lua 脚本 (CraftStudio) 的应用程序中一样,都使用 Lua 5.1。

好像发生在什么时候

  • (条目数) <索引(第一个例子)
  • (条目数) < index-1 (对于第二个例子)

那么,这是预期的行为吗,是 Lua 5.1 的错误吗?是否有另一个公式可以预测这是否会发生?

非常感谢

最佳答案

一个表只有当它的索引是连续的时才是一个列表:t[1], t[2], t[3], ... t[i], ... t[N] 是非零的所有 i 从 1 到 N。您的代码使用表作为关联数组(C++ 中的映射,Python 中的字典),因此表操作将不起作用(实际上,它们有时可能会起作用,因为它是未定义的行为)。来自 Lua 5.1 引用手册:

Most functions in the table library assume that the table represents an array or a list.

不幸的是,ref 手册没有明确定义“数组或列表”,但是浏览 ref man 讨论数组的地方表明两个简单的规则足以成为“常规”或“普通”数组:t 没有 nil 值[i] 对于 i=1 到 N。

对于 i=1 到 N,您最好创建一个 t[i]=0 的表,其中 N 大于您在该函数调用中期望的任何值(例如,其他表中的最大值)。完成插入后,您可以将所有剩余的 t[i] which = 0 设置为 nil,但只有在您不需要表操作时才这样做。

你可以做的另一件事是,如果你发现应该在 i 之前插入一个项目,检查 t[i-1] 是否为 nil;如果是,将其设置为 0 或 -1 或表示“虚拟”的某个值。对 i-2 等重复此检查。

关于lua - table.insert 覆盖现有索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20354839/

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