Jump to content




Best way to do an ordered table with named elements


  • You cannot reply to this topic
2 replies to this topic

#1 Inumel

  • Members
  • 120 posts

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 by Inumel, 12 March 2014 - 09:16 AM.


#2 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

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 by theoriginalbit, 12 March 2014 - 09:30 AM.


#3 Inumel

  • Members
  • 120 posts

Posted 12 March 2014 - 09:47 AM

Thanks a million! Works perfectly. In case you were curious, heres my(extremely messy) code





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users