如果用一下代码执行,会发现表并没有被清空,只是删除了1、3、5
horse_race_list = {1,2,3,4,5,6}
for k,v in pairs(horse_race_list) do
if true then
--horse_race_list[k] = nil
table.remove(horse_race_list,k)
end
end
do
for k=1,#horse_race_list do
print('k=',k,horse_race_list[k])
end
end
但是如果用下面的代码执行,表就可以清空了。
horse_race_list = {1,2,3,4,5,6}
for k,v in pairs(horse_race_list) do
if true then
horse_race_list[k] = nil
--table.remove(horse_race_list,k)
end
end
do
for k=1,#horse_race_list do
print('k=',k,horse_race_list[k])
end
end
这是因为使用table.remove的时候,会移动table的索引,导致2、4、6都被跳过了,这点在写代码的时候很容易出现,并且这个bug还不好发现。在此记下,以防再次发生类似的事情。直接使用 horse_race_list[k] = nil置空表的内容就可。
本文对比两种Lua中清空表的方法,发现直接设置元素为nil比使用table.remove更有效。后者因索引移动问题易遗漏元素,前者则能避免此bug。
623

被折叠的 条评论
为什么被折叠?



