Quantcast Print table in order ? - WoWInterface
Thread Tools Display Modes
01-24-13, 05:03 AM   #1
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?

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" )
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
A Flamescale Wyrmkin
AddOn Author - Click to view addons
Join Date: Oct 2009
Posts: 125
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's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,616
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:

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

	local sort = table.sort
	function pairsByKey(t)
		local i = 1
		for k in pairs(t) do
			temp[i] = k
			i = i + 1
		for j = i, #temp do
			temp[i] = nil
		iv, vals = 0, t
		return iter
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.
Author/maintainer of Grid, PhanxChat, oUF_Phanx, and many more.
Troubleshoot an addonTurn any code into an addonMore addon resources
Need help with your code? Post all of your actual code! Attach or paste your files.
Please don’t PM me about addon bugs or code questions. Post a comment or forum thread instead!
  Reply With Quote
01-25-13, 05:34 PM   #4
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 ?

Thread Tools
Display Modes

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