lua-users home
lua-l archive

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

It seems to be a simple and flexible method, thank you and Enrico

2011/10/18 steve donovan <>
On Tue, Oct 18, 2011 at 8:27 AM, Victor Young <> wrote:
> I've considered this method before. It's useful, but when the table has many
> keys, it will be troublesome and easy to make mistakes. Thanks any way!

That's true, so let's see if there's a better notation

t = ordered {
 {a = 1},
 {b = 2},
 {c = 3}

function ordered (spec)
  local t = { _keys = {} }  -- our output table, containing keys array
  for i,pair in ipairs(spec) do
     local k,v = next(pair)
     t[k] = v
     t._keys[i] = k
  return t

that is, you end up with {a=1,b=2,c=3,_keys={'a','b','c'}}

Note the trick with the next() function - gets the first key-value pair!

Now you can do

for _,key in ipairs(t._keys) do
  local value = t[key]

steve d.

steve d.