lua-users home
lua-l archive

RE: LeftJoins with tables (removing values from tables)

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


You would store the collection's objects as keys of a table.
The values relative to each key would be used to store whatever you want.
For example:
local mt = {__mode = "k"}
local t1 = setmetatable({}, mt) -- collection t1
t1[obj1] = true -- insert obj1 into collection t1
t1[obj2] = true -- insert obj2 into collection t1
local t2 = setmetatable({}, mt) -- collection t2
t2[obj2] = true -- insert obj2 into collection t2
So the subtract function would be for example:
function subtract(t1, t2)
	local r = {}
	for k, v in pairs(t1) do
		if not t2[k] then
			r[k] = v
		end
	end
	return r
end
Milano
From: Clemens Wacha <clemens.wacha@gmx.net>
Reply-To: Lua list <lua@bazar2.conectiva.com.br>
To: Lua list <lua@bazar2.conectiva.com.br>
Subject: LeftJoins with tables (removing values from tables)
Date: 2004年9月25日 14:51:09 +0000
Hello,
Very often I have collection of objects and I want to know which
objects from both collections are in common or are only in one of
them.
For this I have created the following pseudo code function that
subtracts one table from the other
-- subtracts all elements in table2 from table1
function( table1, table2)
 tmp = copy of table1
 for all objects in table1 do
 if there is one too in table2
 remove it from tmp
 end
 end
 return tmp
end
In lua I made a deep copy of the table and tried to achieve this
using table.remove but this function sucks somehow. Since i am
removing elements from a table the index changes inside the table
and this prevents me from _efficiently_ finding the objects to
remove.
Now my question: Can I travel a table using for in Lua AND remove
objects form the same table inside the for loop?
for key, value in table do
 if value == "object_to_delete" then
 table.remove(table, key)
 end
end
Thanks
--
Clemens Wacha wacha@gmx.ch ICQ:12620942
successfully using Linux since 1999. See http://www.debian.org
_________________________________________________________________
MSN Messenger: converse com os seus amigos online. http://messenger.msn.com.br

AltStyle によって変換されたページ (->オリジナル) /