lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I tested this -- it works. If you really want to totally get rid of the bad 
stuff, you need a second loop to delete from dst to #tab, but what I did is I 
just set tab[dst] to nil so that an iPairs() would stop after the last valid 
character, and #tab would be the subscript of the last valid character.

The second loop is just to print out the stuff. The filtering all happened in 
the first loop:

#!/usr/bin/lua 
local tab = {"a", "a", "c", "a", "d", "a" }
local dst = 1
for src, val in ipairs(tab) do    --assume tight array, otherwise use while
	if src~=dst and val ~= "a" then
		tab[dst] = val
		dst = dst + 1
	end
end

tab[dst] = nil
for src, val in ipairs(tab) do    --stop at the nil you just inserted
	print(val)
end



On Thursday 13 January 2011 23:12:40 Emmanuel Oga wrote:
> Hello, I'm looking for the best proper way of doing this:
> 
> local tab = {"a", "a", "c", "a", "d", "a" }
> 
> for index, val in ipairs(tab) do
>   if val == "a" then -- could be any other complex condition
>     table.remove(tab, index)
>   end
> end
> 
> -- WRONG: tab = { "a", "c", "d" }, should be { "c", "d" }
> 
> So removing elements from a container _while you are iterating it_ is
> wrong in most languages. I'm looking for the nicest and proper way of
> doing it.
> 
> Two methods I came up with:
> 
> 1) popping from the array and pushing to a new one if the condition is met.
> 2) Iterating first, storing indexes to remove, then removing one by
> one (compensating index offset as a result of each removed elements)
> 
> http://pastie.org/1458808
> 
> Is there any other more elegant way?
> 
> --------------------------------------------------------------
> EmmanuelOga.com - Software Developer
>