【发布时间】: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.* 函数)仅被定义为对没有孔的类数组表进行操作。无法保证它们在表包含孔时的行为。