如何从数组中删除所有 'nil' 值?

我有一个对象数组(或仅为数字),还有另一个数组,其中包含不应在任何情况下从第一个数组中删除的所有对象。它看起来像这样:

-对象数组(现在仅为数字)
对象= {}

-应始终保留在“对象”数组中的对象数组
DontDestroyThese = {}

-填充数组
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,以使Objects数组仅包含调用destroy()后留在那里的数字。我该如何做到这一点?

点赞
用户3828960
用户3828960

最有效的方法可能是创建一个新的表来保存结果。尝试在数组中移动值可能会比简单地附加到新表中产生更高的开销:

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

这种方法也意味着您无需处理正在迭代的表/数组的内容的更改。

2015-02-03 12:08:40
用户2328287
用户2328287
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

-- 仅移除偶数
local t = remove({1, 2, 3, 4}, even)

-- 移除指定值
local function keep(t)
  return function(v)
    return not t[v]
  end
end

remove(Objects, keep(DontDestroyThese))
2015-02-03 12:30:59
用户3735873
用户3735873

我认为解决方案要简单得多。为了移除数组中的任何nil元素(“洞”),您只需要使用pairs()迭代表,这将跳过任何nil元素,仅返回您添加到新的本地表中的非nil值,在“cleanup”函数的末尾返回。数组(索引从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          --将“洞”创建在“d”处
show(t)             --> a b c
t = CleanNils(t)    --移除“洞”
show(t)             --> a b c e f
2015-02-03 15:43:42