WoWInterface

WoWInterface (https://www.wowinterface.com/forums/index.php)
-   Lua/XML Help (https://www.wowinterface.com/forums/forumdisplay.php?f=16)
-   -   Print table in order ? (https://www.wowinterface.com/forums/showthread.php?t=45719)

skarie 01-24-13 05:03 AM

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.

humfras 01-24-13 05:15 AM

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)

Phanx 01-24-13 09:47 PM

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.

skarie 01-25-13 05:34 PM

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.


All times are GMT -6. The time now is 12:01 PM.

vBulletin © 2024, Jelsoft Enterprises Ltd
© 2004 - 2022 MMOUI