Thread Tools Display Modes
01-24-13, 05:03 AM   #1
skarie
An Aku'mai Servant
AddOn Author - Click to view addons
Join Date: Jun 2011
Posts: 37
Print table in order ?

How do I print this array/table in order every time without changing the structure of it?

Code:
local rbuffs = {	["Bloodlust Heroism"] = false,
					["Attack Power"] = false,
					["Attack Speed"] = false,
					["Critical Strike Chance"] = false,
					["Mastery"] = false,
					["Spell Haste"] = false,
					["Spell Power"] = false,
					["Stamina"] = false,
					["Stat Multiplier"] = false,
}
for k,v in pairs(rbuffs) do
print( k.. "\n" )
end
Is there something in lua that allows me to iterate through the above array/table in a predictable manner? Thanks.
  Reply With Quote
01-24-13, 05:15 AM   #2
humfras
A Flamescale Wyrmkin
AddOn Author - Click to view addons
Join Date: Oct 2009
Posts: 131
You need to define an interator function.

See http://www.lua.org/pil/19.3.html for reference.
(the 'pairsByKeys' function example should be exactly what you want)
__________________
Author of VuhDo CursorCastBar OptiTaunt Poisoner RaidMobMarker
  Reply With Quote
01-24-13, 09:47 PM   #3
Phanx
Cat.
 
Phanx's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,617
I'd strongly recommend not using the function on that linked page, as it wastes memory creating a new table and a new function every time you call it. Something like this should work the same without creating new objects on every call:

Code:
local pairsByKey
do
	local temp = {}
	
	local iv, vals = 0
	local iter = function()
		iv = iv + 1
		if temp[iv] == nil then
			return nil
		else
			return temp[iv], vals[temp[iv]]
		end
	end

	local sort = table.sort
	function pairsByKey(t)
		local i = 1
		for k in pairs(t) do
			temp[i] = k
			i = i + 1
		end
		for j = i, #temp do
			temp[i] = nil
		end
		sort(temp)
		
		iv, vals = 0, t
		return iter
	end
end
However, if you find yourself needing a solution like this, I'd be strongly inclined to say you're approaching the problem the wrong way, and there is probably a better way to write your code that doesn't require these kind of tricks.
__________________
Retired author of too many addons.
Message me if you're interested in taking over one of my addons.
Don’t message me about addon bugs or programming questions.
  Reply With Quote
01-25-13, 05:34 PM   #4
skarie
An Aku'mai Servant
AddOn Author - Click to view addons
Join Date: Jun 2011
Posts: 37
Thanks guys for the help. It looks like I am going to have to change the structure of my array to include indices. Otherwise, any sorting function will kill my cpu cycles.
  Reply With Quote

WoWInterface » Developer Discussions » Lua/XML Help » Print table in order ?


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off