  lua-l archive

• Subject: Re: how to get the prev/next element of table FAST?
• From: Axel Kittenberger <axkibe@...>
• Date: Sat, 15 Jan 2011 11:37:28 +0100

In my opinion you mixed some things up, In C you have to travese an
array as well to get the index of a value in it, without having a
hashtable to store the indexes.

> local t = {'x', d', 'e', 'f', 'n'} (I randomized the values so less confusion)

This means in Lua
t = 'x'
t = 'd'
t = 'e'
t = 'f'
t = 'n'

So if you have the key 2, its position is 2! Easy as that. If you have
the value 'd' you need to either run through i/pairs() or have a
second table for value -> key.

A C is in no way different:

*p -> 'x'
*(p+1) -> 'd'
*(p+2) -> 'e'
*(p+3) -> 'f'
*(p+4) -> 'n'

On Sat, Jan 15, 2011 at 3:12 AM, Xavier Wang <weasley.wx@gmail.com> wrote:
> hi all.
> In C, to get prev/next element of a array is easy: we just use
> pointer arithmetic to get the index of the element. and increase/decrease
> the index to get prev/next value in array.
> but in Lua, the table is a mixing of array and hash-table. so we can not get
> the corresponding key for the value. so, how can I made a FAST function just
> like table.getkey() ?
> local t = {'a', 'b', 'c', 'd', 'e'}
> print(table.getkey(t, 'b')) --> 2
> I did it by associate index with value, but I must maintain the table of
> index if I insert/remove something from the table. there are some good way
> to do this?