Popping all items from a table

It can often be very useful to iterate through all the elements of a table or associative array. This is more problematic when you don't know how many indexes there are with dynamic data structures.]

Many languages support a 'for each... in... ' structure.

This code illustrates the approach with Lua.


while table.getn(table_name) > 0 do
	local element = table.remove(table_name, 1)
end
What does this code do?

table_name is the identifier of the table.

getn returns the number of elements in the table.

As elements are removed from the table they are assigned to the local variable called, 'element'.

When an element is removed the indexes are changed so that the first index always points to the next item in the table.

Note, Lua tables are one-indexed not zero-indexed.