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

标签 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+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/

相关文章:

ruby - 使用特定规则拆分字符串的最干净的 ruby​​ 代码

python - 将字节数组转换为字符串spark

for-loop - string.match 在 Lua for 循环中不起作用

null - 如果 _N_ = 1 条件返回 true,即使在 SAS 中设置的数据集为空(零观察)

sql-server - 基于JOIN两个表的SQL Server View -如何用空格替换NULL值?

python - 如何在一组已排序数组中找到最大的连续重叠区域

php - 另一个数组内的 stdClass 对象数组

class - 构建 Lua 类

lua - 窗口 :94:arguments must be the same length stand for? 是什么意思

java - 始终返回 null 的方法