[英]How to remove all 'nil' values from an array?
我有一個對象數組(或只是數字),還有另一個數組,其中包含所有在任何情況下都不應從第一個數組中刪除的對象。 看起來像這樣:
-- 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
數組中包含的Objects
除外。 該方法如下所示:
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()
之后留在那里的數字組成。 我怎么做?
最有效的方法可能是創建一個新表來保存結果。 嘗試在數組中四處移動值可能會比簡單地追加到新表上具有更高的開銷:
function destroy()
local tbl = {}
for I = 1, #Objects do
if(DontDestroyThese[Objects[I]] ~= nil) then
table.insert(tbl, Objects[I])
end
end
Objects = tbl
end
此方法還意味着您不必處理要迭代的表/數組的內容。
我認為解決方案要簡單得多。 要刪除任何nil(數組中的“空洞”),您需要做的就是使用pairs()迭代表。 這將跳過所有僅返回您添加到在cleanup函數末尾返回的新本地表中的非nil值的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
local function remove(t, pred)
for i = #t, 1, -1 do
if pred(t[i], i) then
table.remove(t, i)
end
end
return t
end
local function even(v)
return math.mod(v, 2) == 0
end
-- remove only even numbers
local t = remove({1, 2, 3, 4}, even)
-- remove values you want
local function keep(t)
return function(v)
return not t[v]
end
end
remove(Objects, keep(DontDestroyThese))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.