lua-users home
lua-l archive

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

>When we try to retrieve the keys in the order:
>we get all keys, but (as far as we can tell) in a more or less random order...

Tables in Lua are implemented as hash tables, and so the order is as you say
more or less random. The manual does not say this for lua_next, only for next:

 The order in which the indices are enumerated is not specified, even
 for numeric indices (to traverse a table in numeric order, use a
 numerical for or the function foreachi).

If you must visit the table in a given order, then you have to use a auxiliary
table for this. For instance, if you know the names of the keys beforehand,
then you can do something like this:

	local keys={"GENERAL", "ID", "BCD", ... }
	for i=1,getn(keys) do
	  local k=keys[i]
	  process(k,t[k])		-- where `t' is your table

I'll leave the translation of this to C as an exercise...

If you don't know the keys in advance, then perhaps you could change the 
format of the file to move the name of the filed into its value, follows:

 BLOCK_3 =
   { _="GENERAL"; 'Something else', 'prompt', 'help'},
   {_="Id";	'Id' , 'RT'  , 'NNTS'  , '2', '0', 'H'},
   {_="Bcd";	'-', '0101', 'BCD'   , '2', '0', 'H'},

Then you can traverse the table as an array, ie, from 1, 2, ... getn.