【问题标题】:table.insert override existing indextable.insert 覆盖现有索引
【发布时间】:2013-12-19 17:28:07
【问题描述】:

回答:仅在序列(数组/列表)上使用 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。

好像是什么时候发生的

  • (条目数)
  • (条目数)

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

非常感谢

【问题讨论】:

  • table.insert (实际上是所有的 table.* 函数)仅被定义为对没有孔的类数组表进行操作。无法保证它们在表包含孔时的行为。

标签: lua lua-table


【解决方案1】:

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

表格库中的大多数函数都假设表格代表 数组或列表。

不幸的是,参考手册没有明确定义“数组或列表”,但浏览参考手册讨论数组的地方表明两个简单的规则足以成为“常规”或“普通”数组: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 等重复此检查。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-05-09
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多