这个问题类似于如何在删除键但是明显不同的情况下安全地迭代lua表.
给定一个Lua数组(具有1从中开始的顺序整数的键的表),迭代这个数组并删除一些条目的最佳方法是什么?
我在Lua数组表中有一组带时间戳的条目.条目总是添加到数组的末尾(使用table.insert).
local timestampedEvents = {}
function addEvent( data )
table.insert( timestampedEvents, {getCurrentTime(),data} )
end
Run Code Online (Sandbox Code Playgroud)
我需要偶尔遍历此表(按顺序)并处理并删除某些条目:
function processEventsBefore( timestamp )
for i,stamp in ipairs( timestampedEvents ) do
if stamp[1] <= timestamp then
processEventData( stamp[2] )
table.remove( timestampedEvents, i )
end
end
end
Run Code Online (Sandbox Code Playgroud)
不幸的是,上面的代码方法打破了迭代,跳过了一些条目.有没有比手动走索引更好(更少打字,但仍然安全)的方法:
function processEventsBefore( timestamp )
local i = 1
while i <= #timestampedEvents do -- warning: do not cache the table length
local …Run Code Online (Sandbox Code Playgroud) lua ×1