我有一个对象数组(或只是数字),还有另一个数组,其中包含在任何情况下都不应从第一个数组中删除的所有对象。它看起来像这样:
-- Array of objects (just numbers for now)
Objects = {}
-- Array of objects that should always stay in the 'Objects' array
DontDestroyThese = {}
-- Populate the arrays
Objects[#Objects+1] = 1
Objects[#Objects+1] = 2
Objects[#Objects+1] = 3
Objects[#Objects+1] = 4
Objects[#Objects+1] = 5
DontDestroyThese[#DontDestroyThese+1] = 2
DontDestroyThese[#DontDestroyThese+1] = 5
现在,我有一个名为 destroy()
的方法,该方法应该从 Objects
数组中删除除 DontDestroyThese
数组中包含的对象之外的所有对象。该方法看起来像这样:
function destroy()
for I = 1, #Objects do
if(DontDestroyThese[Objects[I]] ~= nil) then
print("Skipping " .. Objects[I])
else
Objects[I] = nil
end
end
end
但是,结果是,Objects
数组现在到处包含 nil
值。我想删除这些 nil
,以便 Objects
数组仅包含调用 destroy()
后留下的数字。我该怎么做?
最佳答案
我认为解决方案要简单得多。要删除任何 nils(数组中的“洞”),您所需要做的就是使用pairs() 迭代您的表。这将跳过任何 nils,仅返回您添加到“cleanup”函数末尾返回的新本地表中的非 nil 值。数组(索引从 1..n 开始的表)将保持相同的顺序。例如:
function CleanNils(t)
local ans = {}
for _,v in pairs(t) do
ans[ #ans+1 ] = v
end
return ans
end
那么你只需要这样做:
Objects = CleanNils(Objects)
测试它:
function show(t)
for _,v in ipairs(t) do
print(v)
end
print(('='):rep(20))
end
t = {'a','b','c','d','e','f'}
t[4] = nil --create a 'hole' at 'd'
show(t) --> a b c
t = CleanNils(t) --remove the 'hole'
show(t) --> a b c e f
关于arrays - 如何从数组中删除所有 'nil' 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28298358/