lua-users home
lua-l archive

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


Ando,

I may have misunderstood your question, but wouldn't a metatable around the
function bellow (untested) do it?

function add(table, key, value)
    if table.n == nil then
        table.n = 1
    else
        table.n = table.n + 1
    end
    table[key] = value
    table[table.n] = key
end

t={}
add(t, 'a', function() ... end)
add(t, 'b', function() ... end)

print(t[1]) -- prints 'a'
print(t[2]) -- prints 'b'

The only problem occurs when you want to use numbers as keys, but that can
be addressed via a proxy table.

Andre de Leiradella
http://www.geocities.com/andre_leiradella/

------------------- mensagem original -------------------

Subject: Direct access to key/value table items?
From: Ando Sonenblick <ando@...>
Date: Sat, 09 Aug 2003 16:04:00 -0700

Gang,

I've got many a table like this:

t = {
    a = function() ... end,
    b = function() ... end
    }

I know need to get an indexed function name from the table.  For index 1, I
need back "a", index 2, "b" and so on.

This can be done with foreach, but is there no way in lua to directly access
a specific item?

Such as:

print(t[1].key) ????

Thx,
Ando

-----------------
SpriTec Software
www.spritec.com