lua-users home
lua-l archive

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


On Tue, Jul 20, 2010 at 2:38 AM, Valerio Schiavoni
<valerio.schiavoni@gmail.com> wrote:
> In general, what is the approach in using complex datatypes as keys in tables?

in general, mutable types aren't so useful as keys; since you can't
'rebuild' them:

> t1={1,2}
> =t1
table: 0x18cdff0
> t2={1,2}
> =t2
table: 0x18ce8f0

that's obvious if you remember that the '{}' operator is a constructor.

the simplest answer is that if you need 'complex' keys, it's easier to
serialize them into a string that reflects exactly the 'unicity' you
want.  sometimes you don't really have to bother with deserialization.

a simple case:

function tokey (t)
  return table.concat (t, ',')
end

sometable = { [tokey{1,2}] = 'somevalue'}
sometable[tokey{3,'xy'}] = "three x and y's"

=sometable[tokey{1,2}]
    => somevalue
=sometable[tokey{3,'xy'}]
    => three x and y's


it's not too nice; but it does work.  for more complex cases you
better pass around some 'token' objects instead of relying on
'rebuilding' the keys.

-- 
Javier