【发布时间】:2015-04-02 14:47:14
【问题描述】:
我有一个对象数组(或只是数字),我还有另一个数组,其中包含在任何情况下都不应从第一个数组中删除的所有对象。它看起来像这样:
-- 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 值。我想删除这些nils,以便Objects 数组只包含调用destroy() 后留下的数字。我该怎么做?
【问题讨论】:
-
你试过
table.remove(Objects, I)吗? -
Objects[#Objects] = 1并没有像你想象的那样做,因为 Lua 中的数组从索引 1 开始。试试Objects[#Objects+1] = 1。 -
我同意@lhf 的评论。
DontDestroyThese[#DontDestroyThese]也是如此 - 您必须添加+1 -
缺少
+1是我在输入代码示例时犯的一个错误。 -
@manabreak 你使用了错误的术语。对象不包含“这里和这里”的 nil。它包含漏洞,因为在 Lua 中将 nil 分配给 table[key] 意味着“删除密钥”。