我有一个对象数组(或仅为数字),我还有另一个数组,其中包含不应在任何情况下从第一个数组中删除的所有对象。它看起来像这样:
-- 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()
后剩下的数字。我该怎么做?
table.remove(Objects, I)
吗? - greatwolfObjects[#Objects] = 1
并不会像你想象的那样运行,因为在 Lua 中数组的索引从 1 开始。请尝试使用Objects[#Objects+1] = 1
。 - lhfDontDestroyThese[#DontDestroyThese]
也是一样 - 你必须添加一个+1
。 - kikito+1
是我在输入代码示例时犯的错误。 - manabreak