Arrays 在阅读了这个答案后,我理解了它的好处,但对它的功能感到困惑
我希望使用lua从表中删除一项 快速搜索使我阅读了该表。由于效率原因,remove()是个坏主意 然而,我不是100%理解自定义函数 下面是函数Arrays 在阅读了这个答案后,我理解了它的好处,但对它的功能感到困惑,arrays,lua,Arrays,Lua,我希望使用lua从表中删除一项 快速搜索使我阅读了该表。由于效率原因,remove()是个坏主意 然而,我不是100%理解自定义函数 下面是函数 function ArrayRemove(t, fnKeep) local j, n = 1, #t; for i=1,n do if (fnKeep(t, i, j)) then -- Move i's kept value to j's position, if it's not already there.
function ArrayRemove(t, fnKeep)
local j, n = 1, #t;
for i=1,n do
if (fnKeep(t, i, j)) then
-- Move i's kept value to j's position, if it's not already there.
if (i ~= j) then
t[j] = t[i];
t[i] = nil;
end
j = j + 1; -- Increment position of where we'll place the next kept value.
else
t[i] = nil;
end
end
return t;
end
我理解我们在一个循环中移动项目并删除所有内容,而不是表。remove()必须移动所有内容(这里有一个很长的答案,)
查看上面的函数,如果要删除的项目是第一个项目,会发生什么情况
如果我们替换行if(fncepe(t,i,j)),那么
建议使用(t[i]=='deleteme')
然后什么也不会发生,因为i和j都是1
另外,如果第一个“if”为false,那么该项无论如何都会被删除
有人能帮我解释一下吗
编辑
我认为工作职能如下
local j, n = 1, #t -- t is table to iterate over
for i = 1, n do -- begin the loop
if t[i] ~= 'object to delete' then -- if this is NOT the item to remove
if i ~= j then -- can it be moved to new position
t[j] = t[i] -- move to new pos
t[i] = nil -- clear old pos
end
j = j + 1 -- increment the new pos counter
end
else -- if it is the item TO delete then delete it
t[i] = nil
end
我认为这是一个输入错误,在标题为
Bonus(高级用户)
的部分中,他们为if语句显示了这一行if(v['name']=='Rick'),然后--保留“Rick”。
带有if语句的行应该是你想要保留的而不是删除的,else语句处理刚刚删除的值。谢谢,这更有意义,我将为碰巧正在查看的任何其他人在我的问题中添加一个编辑