12.07.2015 Views

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5 ■ Advanced Functions <strong>and</strong> Control Structures 89stack traceback:[C]: in function 'sort'stdin:1: in main chunk[C]: ?The table.sort() function takes a second argument specifically <strong>for</strong> thispurpose, to allow the programmer to define how values should be compared.This function takes two arguments, <strong>and</strong> returns true if the first argument isless than the second argument, <strong>and</strong> false if the second argument is less thanor equal to the first argument. That means you can sort two tables based ontheir member fields, or some other criteria you specify. Write the followingfunction, which will compare two <strong>of</strong> the elements based on name:function sortNameFunction(a, b)return a.name < b.nameendAlthough the function is extremely short, that’s all that is required to sort thearray by name. Pass this function in as the second argument to table.sort():> table.sort(guild, sortNameFunction)> <strong>for</strong> idx, value in ipairs(guild) do>> print(idx, value.name)>> end1, Cladhaire2, Deathsquid3, DraoiTo reverse the sort order, just reverse the order <strong>of</strong> the comparison (note thatthe position <strong>of</strong> b.name <strong>and</strong> a.name inthecomparisonhavechanged):function sortNameFunctionDesc(a, b)return b.name < a.nameendSort with this new function:> table.sort(guild, sortNameFunctionDesc)> <strong>for</strong> idx, value in ipairs(guild) do print(idx, value.name) end1, Draoi2, Deathsquid3, Cladhaire<strong>Creating</strong> a More Complex Sort FunctionAssume you’d like to sort the preceding data by level <strong>and</strong> then by charactername. You can write a function to sort by level, but there’s no way to tell in

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!