lua-users home
lua-l archive

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


On 03/30/2012 05:13 AM, Patrick Rapin wrote:
The hash array is by nature unsorted. It is impossible to get back the
same order as the construction.
If you need it, you must use numeric indexes (a sequence), or an
associated array with keys order.


If you only intend to use strings for primary keys, then you can use integer keys to specify the order.

mydata = {
  key1 = "value1",
  key2 = "value2",
  -- I'm writing the integer indexes to be explicit,
  -- but they're not required as Lua will assign to
  -- consecutive integers by itself
  [1] = "key1",
  [2] = "key2"
}

for n,k in ipairs(mydata) do -- `for n=1,#mydata do' works too
  print(k, mydata[k])
end


--
- tom
telliamed@whoopdedo.org