Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua 表1.1插入替代现有索引_Lua_Lua Table - Fatal编程技术网

Lua 表1.1插入替代现有索引

Lua 表1.1插入替代现有索引,lua,lua-table,Lua,Lua Table,答:仅在序列数组/列表表上使用table.*函数,其中只有从1开始的连续整数键。它们的行为在类似于非数组的表上是未定义的:它们可能按照您的预期工作,也可能不按照您的预期工作 在Lua5.1 table.insert t中,如果表中已经存在索引,则值应该向上移动,对吗 但它并不总是这样: local t = {} table.insert( t, 4, 5 ) table.insert( t, 5, 6 ) table.insert( t, 4, 4 ) -- this erase the val

答:仅在序列数组/列表表上使用table.*函数,其中只有从1开始的连续整数键。它们的行为在类似于非数组的表上是未定义的:它们可能按照您的预期工作,也可能不按照您的预期工作

在Lua5.1 table.insert t中,如果表中已经存在索引,则值应该向上移动,对吗

但它并不总是这样:

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
但是:

这与LuaForWindows命令行以及运行LuaScriptsCraftStudio的应用程序中的情况类似,两者都使用Lua5.1

似乎它发生在

第一个示例的条目数<索引 第二个示例的条目数<索引-1 那么,这是一个预期的行为,是Lua5.1的一个bug吗? 有没有其他公式可以预测这种情况是否会发生


非常感谢

只有索引连续时,表才是列表:t[1]、t[2]、t[3]、。。。t[i]。。。T(n]对所有i都是非零的,从1到n。您的代码使用表作为C++中的关联数组映射,在Python中使用字典,因此表操作实际上不能工作,有时可能会工作,因为它是未定义的行为。从Lua 5.1参考手册:

表库中的大多数函数都假定表表示 数组或列表

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

对于i=1到N,您最好创建一个t[i]=0的表,其中N比您在该函数调用中期望的任何值都大,例如,其他一些表中的最大值。一旦完成了插入,就可以将所有剩余的t[i]设置为nil,但只有在不需要表ops的情况下才能这样做


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

仅当表的索引是连续的:t[1]、t[2]、t[3]、。。。t[i]。。。T(n]对所有i都是非零的,从1到n。您的代码使用表作为C++中的关联数组映射,在Python中使用字典,因此表操作实际上不能工作,有时可能会工作,因为它是未定义的行为。从Lua 5.1参考手册:

表库中的大多数函数都假定表表示 数组或列表

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

对于i=1到N,您最好创建一个t[i]=0的表,其中N比您在该函数调用中期望的任何值都大,例如,其他一些表中的最大值。一旦完成了插入,就可以将所有剩余的t[i]设置为nil,但只有在不需要表ops的情况下才能这样做


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

table.insert和所有table.*函数仅定义用于在类似数组的无孔表上进行操作。无法保证它们在表包含孔时的行为。table.insert和所有表。*函数仅定义用于对类似数组的无孔表进行操作。无法保证它们在表中包含孔时的行为。Lua 5.2手册明确谈到序列:。Lua 5.2手册明确谈到序列:。
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