lua-users home
lua-l archive

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

It sounds to me like what you are trying to do is retain the order of key insertion.

The technique I usually use (for tables with string keys) is to insert the keys into the table as well:

local mytable = {}
for i = 1, mytable.n do
  local name, info = readInfo(i) -- Note 1
  mytable[i], mytable[name] = name, info

This assumes that all the names will be unique, which is not always the case. (It would be easy to check, though)

Then you can access by name:  mytable[key]
or by index: mytable[mytable[i]]

You can loop over all the keys in numeric order:

for i, key in ipairs(mytable) do
  local val = mytable[key]

(You could write a custom iterator to do that, if you prefer)

If the keys are repeated (which is common in parsing internet protocols) you need something more subtle, but it can be done.

Note 1:
  local name, info
  name, info = readInfo(i)

compiles into (in effect):
  local name, info = nil, nil
  local tmp1, tmp2 = readInfo(i)
  name = tmp1
  info = tmp2
  local name, info = readInfo(i) is a bit faster

On 1-Sep-05, at 6:52 AM, Jose Marin wrote:

The solution I've found is to have a 'n' field on the
table, and update it when I insert a new entry on the

local mytable = { n = 0 }

for i = 1, readInfoCount()
   local name, info

   name, info = readInfo(i)

   mytable[name] = info

   mytable.n = mytable.n + 1



Will print the number of members of the table,
alright, but the problem is if I have a field named
like "n"...

I could use _n, tableSize or other name to keep the
table size, but I wonder if there is one clever way of
do this...

Anyway, thank you all for the tips!

Another question is if it's possible to get a table
field using an index, on a non numerical indexed

Yes, I could use foreachi ... but there is a direct
way of do this?

Converse com seus amigos em tempo real com o Yahoo! Messenger