This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Inumel's profile picture

Best way to do an ordered table with named elements

Started by Inumel, 12 March 2014 - 08:13 AM
Inumel #1
Posted 12 March 2014 - 09:13 AM
I have discovered that if you name every element inside a table, IE


testtab = {
  ["test1"]=test1
  ["test2"]=test2
  ["test3"]=test3
}
ect, makes ipairs no longer use able(unless im doing something very wrong)
So I was wondering the best way to go about ordering these, and I think thats using meta tables.. But I am very inexperienced with those and not too sure where to start. So i ask here, in case anybody can help, or suggest a less painful method :)/>
Edited on 12 March 2014 - 08:16 AM
theoriginalbit #2
Posted 12 March 2014 - 09:29 AM
the reason ipairs doesn't work is because it is designed to work with indexes (hence the i) using strings is referred to as keys.

now I'm sure as you know there is no order guaranteed with the pairs function either. so what is the solution then? well you're going to have to implement your own 'pairs' like function; I propose the following code

local function orderedPairs( _t )
  local keys = {} --# lets make a list of all the keys, and only the keys, they will be stored numbered!
  for k in pairs(_t) do
	table.insert(keys, k) --# insert the keys into the table
  end
  table.sort(keys) --# this is the important line! this puts the keys in order
  local index = 0 --# this is the index we're currently accessing
  return function()
	index = index + 1 --# increment the index
	local key = keys[index] --# get the key
	return key, _t[key] --# return the key and the value from the original table
  end
end
and with the usage of

for k,v in orderedPairs(testtab) do
  print(k, ' : ', v)
end

Quick side note: It has been previously discussed and we have all come to the conclusion that you're better to use a standard for loop over ipairs, it adds no extra benefit, it actually slows it down, by using ipairs.
Edited on 12 March 2014 - 08:30 AM
Inumel #3
Posted 12 March 2014 - 09:47 AM
Thanks a million! Works perfectly. In case you were curious, heres my(extremely messy) code