lua-users home
lua-l archive

[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

	return r


From: Clemens Wacha <>
Reply-To: Lua list <>
To: Lua list <>
Subject: LeftJoins with tables (removing values from tables)
Date: Sat, 25 Sep 2004 14:51:09 +0000


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

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
 return tmp

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

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)

Clemens Wacha               ICQ:12620942

successfully using Linux since 1999. See

MSN Messenger: converse com os seus amigos online.