title: Safely remove items from an array table while iterating
body: <p><em>This question is similar to <a href="https://stackoverflow.com/questions/6167555/how-can-i-safely-iterate-a-lua-table-while-keys-are-being-removed">How can I safely iterate a lua table while keys are being removed</a> but distinctly different.</em></p>
  
  <h3>Summary</h3>
  
  <p>Given a Lua array (table with keys that are sequential integers starting at <code>1</code>), what's the best way to iterate through this array <em>and delete some of the entries as they are seen</em>?</p>
  
  <h3>Real World Example</h3>
  
  <p>I have an array of timestamped entries in a Lua array table. Entries are always added to the end of the array (using <code>table.insert</code>).</p>
  
  <pre><code>local timestampedEvents = {}
  function addEvent( data )
    table.insert( timestampedEvents, {getCurrentTime(),data} )
  end
  </code></pre>
  
  <p>I need to occasionally run through this table (in order) and process-and-remove certain entries:</p>
  
  <pre><code>function processEventsBefore( timestamp )
    for i,stamp in ipairs( timestampedEvents ) do
      if stamp[1] &lt;= timestamp then
        processEventData( stamp[2] )
        table.remove( timestampedEvents, i )
      end
    end
  end
  </code></pre>
  
  <p>Unfortunately, the code above approach breaks iteration, skipping over some entries. Is there any better (less typing, but still safe) way to do this than manually walking the indices:</p>
  
  <pre><code>function processEventsBefore( timestamp )
    local i = 1
    while i &lt;= #timestampedEvents do -- warning: do not cache the table length
      local stamp = timestampedEvents[i]
      if stamp[1] &lt;= timestamp then
        processEventData( stamp[2] )
        table.remove( timestampedEvents, i )
      else
        i = i + 1
      end
    end
  end
  </code></pre>