Arrays 如何删除所有';无';数组中的值?
我有一个对象数组(或者仅仅是数字),还有另一个数组,其中包含在任何情况下都不应从第一个数组中删除的所有对象。它看起来像这样:Arrays 如何删除所有';无';数组中的值?,arrays,lua,null,lua-table,Arrays,Lua,Null,Lua Table,我有一个对象数组(或者仅仅是数字),还有另一个数组,其中包含在任何情况下都不应从第一个数组中删除的所有对象。它看起来像这样: -- 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+
-- 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
function destroy()
for I = 1, #Objects do
if(DontDestroyThese[Objects[I]] ~= nil) then
print("Skipping " .. Objects[I])
else
Objects[I] = nil
end
end
end
现在,我有一个名为destroy()
的方法,它应该从对象
数组中删除所有对象,除了dontdestroythes
数组中包含的对象。方法如下所示:
-- 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
function destroy()
for I = 1, #Objects do
if(DontDestroyThese[Objects[I]] ~= nil) then
print("Skipping " .. Objects[I])
else
Objects[I] = nil
end
end
end
但是,因此,
对象
数组现在到处都包含nil
值。我想删除这些nil
s,这样对象
数组将只包含调用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()迭代表。这将跳过任何仅返回非nil值的nil,这些值是您添加到“cleanup”函数末尾返回的新本地表中的。数组(索引为1..n的表)将保持相同的顺序。例如:
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))
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
您是否尝试过
table.remove(Objects,I)
?Objects[#Objects]=1
的作用与您认为的不同,因为Lua中的数组从索引1开始。试试Objects[#Objects+1]=1
。我同意@lhf的评论。dontdestroythes[#dontdestroythes]
-您必须添加一个+1
,即缺少+1
是我在键入代码示例时犯的错误。@manabreak您使用了错误的术语。对象不包含nils“此处和此处”。它包含漏洞,因为在Lua赋值中,表[key]的nil表示“删除键”。为此,不知何故,这些过于简单的解决方案总是让我不知所措