[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Hashing on more than one attribute?
- From: Dirk Laurie <dirk.laurie@...>
- Date: Thu, 8 Nov 2012 07:00:24 +0200
2012/11/8 Marc Lepage <mlepage@antimeta.com>:
> I know it's trivial to hash on a single value, by putting it into a table
> field. I want to effectively store a composite key in a table: say, a
> string, a number, and another string.
>
> Is there a way I can somehow produce a single hash of that combination of
> three values, to use as a key in a field? Something not obvious? Or must I
> effectively have a few levels of tables to hash 3 values? (And more for 4,
> 5, 6 values...)
I suppose this does not qualify for "not obvious", but I concatenate
string representations.
$ lua
Lua 5.2.1 Copyright (C) 1994-2012 Lua.org, PUC-Rio
Patch to use metamethod in table.concat by DPL
> getmetatable""._concat = function(a,b) return tostring(a)..tostring(b) end
> db = {}
> setmetatable(db, {__call =
>> function(tbl,...) return tbl[table.concat{...}] end;
>> __newindex = function (tbl,key,value)
>> if type(key)~="string" then key=table.concat(key) end
>> rawset(tbl,key,value)
>> end
>> })
> db[{"a",1,"b"}]=1234
> print (db("a",1,"b"))
1234
Of course, you can also say `db["a1b"]` or even db.a1b.
And in this example, you don't need my patch or the redefinition
of string __concat: those kick in when you start using objects that
have tostring metamethods.