Help with looping over table values?

Having a bit of trouble here hoped someone could help me. This is mainly a Lua question I believe and doesn’t directly pertain to Corona but nevertheless it is for a Corona project so here goes…

[lua] for i = 1, #myTable do

local tableItem = myTable[i]

if someConditionIsMet then

–Remove the item from the array
table.remove (myTable, i)

end

end[/lua]

The issue I am getting is a runtime error basically saying that tableItem is nil, I believe this is because when I remove the item from the table, I am still iterating over the original table’s length. So this is causing an error because my new table may not have that many items left in it.

Is there a way to loop over a table that has a variable length (i.e. removing and inserting items into it within the loop)?

Thank you for any assistance you can provide. [import]uid: 10747 topic_id: 3723 reply_id: 303723[/import]

Removing is easy, change the first line to: for i = #myTable,1,-1 do
That way you iterate from the end of the table down to the beginning and it won’t cause any problems if you remove an item.

For inserting I’d use a Repeat…Until loop, something like:

[code]
Local i = 1
Repeat
local tableItem = myTable[i]
If someConditionIsMet then
table.insert(myTable,#myTable+1,someValue) – insert at the end
end
i = i + 1
Until i > #myTable

[import]uid: 9064 topic_id: 3723 reply_id: 11329[/import]

Thank you so much! [import]uid: 10747 topic_id: 3723 reply_id: 11377[/import]