lua-users home
lua-l archive

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


On Thursday 02 March 2006 17:15, Jim Mellander wrote:
[...]
> When I want to update the table I tried constructing another anonymous
> table with the exact same keys & values.  This didn't work, I presume
> due to the fact that they pointed to different tables, albeit with the
> same values.

Indeed.

[...]
> connection_record[
> "tcp"..SUBSEP.."1.2.3.4"..SUBSEP.."123"..SUBSEP.."3.4.5.6"..SUBSEP..567"
> ] = whatever
[...]
> This, however, seems kludgy.  Is there a "lua" way to accomplish this
> task more elegantly?

Ouch.

OTOH, don't knock this approach --- it's kludgy all right, but it'll *work*, 
and it's very light on programmer time. (It's worth looking at table.concat, 
though, for constructing your keys.) Efficient searching is an issue, but 
that's frequently not a problem.

If you're looking for something more flexible, then it might be considering 
that what you've got here is basically a database --- it might be worth 
taking a leaf out of an SQL book. 

connection_record[id] = {proto="tcp", source_ip="...", etc}

function find_record(prototype)
	local o = {}
	for id, record in ipairs(connection_record) do
		local found = true
		for key, value in pairs(prototype) do
			if (record[key] ~= value) do
				found = false
				break
			end
		end
		if found then
			table.insert(o, id)
		end
	end
	return o
end

find_record() will now take a prototype element, and will return a list of ids 
of all records that match that element. ({} will match everything.) You can 
then manipulate the records you're interested in by id, which will be much 
more efficient.

Another trick that's useful in similar situations is to use back-and-forth 
mappings. (Not appropriate in this situation, but it sounds like you're doing 
stuff that could use it.) This is mostly useful when you have two primitive 
types that map to each other, such as numbers and strings. For example:

o = {
	[1] = "one",
	[2] = "two",
	[3] = "three",
	["one"] = 1,
	["two"] = 2,
	["three"] = 3
}

This avoids having to do iterative searches when looking for a particular 
value (in either direction).

-- 
+- David Given --McQ-+ 
|  dg@cowlark.com    | "Home is where, when you have to go there, they
| (dg@tao-group.com) | have to take you in." --- Cordelia Naismith
+- www.cowlark.com --+ 

Attachment: pgplLonVTaYtx.pgp
Description: PGP signature