• From: Peter Shook <pshook@...>
• Date: Sun, 10 Aug 2003 16:25:23 -0400

```
Ando Sonenblick wrote:
```
```Based on your description (and the code at
http://lua-users.org/lists/lua-l/2003-06/msg00559) this maps values to keys;
whereas, I want to map indeces into the table to keys...

That is, for a table of key/value pairs, give me the key (or value,
ideally), of the 'nth' item in the table....
```
```
Sorry Ando, I misunderstood your question.

```
It's easy to get lulled into thinking that there is some order to tables, but really there isn't.
```
http://lua-users.org/lists/lua-l/2002-06/msg00370.html

```
So you'll have to keep track of the order that the key/value pairs are added to the table.
```
special = {}
function special.__newindex(tab, key, value)
rawset(tab, key, value)
table.insert(tab, key)
end

t = setmetatable({}, special)
function t.a() return 't.a' end
function t.b() return 't.b' end
function t.c() return 't.c' end

print'foreach'
table.foreach(t, print)

print'order'
for i,k in ipairs(t) do print(i, k, t[k], t[k]()) end

This script outputs:

foreach
1       a
2       b
3       c
a       function: 0x10046528
c       function: 0x10046550
b       function: 0x10046a88
order
1       a       function: 0x10046528    t.a
2       b       function: 0x10046a88    t.b
3       c       function: 0x10046550    t.c

Here is another example that stores the order of the keys in the metatable.

function special()
local mt = {}
function mt.__newindex(tab, key, value)
rawset(tab, key, value)
table.insert(mt, key)
end
return setmetatable({}, mt)
end

function order(tab)
local mt = getmetatable(tab)
local function itr(t, i)
local key
i, key = ipairs(mt, i)
return i, t[key]
end
return itr, tab, 0
end

function pair(tab, i)
local mt = getmetatable(tab)
local key   = mt[i]
local value = tab[key]
return key, value
end

t = special()
function t.a() return 't.a' end
function t.b() return 't.b' end
function t.c() return 't.c' end

print'foreach'
table.foreach(t, print)

print'order'
for n,f in order(t) do print(n, f, f()) end

print'pair'
print(pair(t,1))
print(pair(t,2))
print(pair(t,3))

This script outputs:

foreach
a       function: 0x10046e98
c       function: 0x10046ee8
b       function: 0x10046f40
order
1       function: 0x10046e98    t.a
2       function: 0x10046f40    t.b
3       function: 0x10046ee8    t.c
pair
a       function: 0x10046e98
b       function: 0x10046f40
c       function: 0x10046ee8

- Peter

```