[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Indexing by multiple values
- From: Renato Maia <maia@...>
- Date: Thu, 28 Oct 2010 16:05:10 -0200
On 26 Oct 2010, at 21:47, Cosmin Apreutesei wrote:
Indexing a table by multiple values (a tuple) has been asked
before[1]. I needed that today so I took a shot at it, and the result
is in [2], if anyone finds it interesting, please comment/adjust code.
I followed a different approach for this problem [1] borrowing some
ideas from the way Lua handle strings. My idea was that each tuple
value should be a single value in the Lua state instead of creating
different tables to represent the same tuple and using '__eq' to
change the way they are compared for equality. In other words:
assert(rawequal(tuple.create(1,false,table),
tuple.create(1,false,table)))
The main advantage of this approach is that tuples can be used as
table keys just like any other value. Therefore, there is no need to
implement special tables or complex data structures that work with the
tuples:
t = { [tuple.create(1,false,table)] = "number, boolean and table" }
print(t[tuple.create(1,false,table)]) --> number, boolean and table
A simple way to compare my approach to yours is to think that there is
only a single instance of your "index table" inside my 'tuple' module.
This internal "index table" is used to store all tuples created so
they can be easily recovered when a tuple with the same values is
"created" again.
One downside of my approach is that I need to make this internal
"index table" to contain only weak references so the tuples are
collected as garbage when the application does not have (strong)
references to them anymore. This is particularly cumbersome when you
think about weak references because unlike strings a tuple will be
collected when there application have only weak references to it:
w = setmetatable({}, {__mode="k"})
w[tuple.create(1,2,3)] = true
for _=1,3 do collectgarbage() end
assert(w[tuple.create(1,2,3)] == nil)
[1] http://www.tecgraf.puc-rio.br/~maia/lua/tuple/
--
Renato Maia
Computer Scientist
Tecgraf/PUC-Rio
__________________________
http://www.inf.puc-rio.br/~maia/