Thread: Table Iteration
View Single Post
03-30-13, 11:49 AM   #4
Sharparam
A Flamescale Wyrmkin
 
Sharparam's Avatar
AddOn Author - Click to view addons
Join Date: Oct 2011
Posts: 102
If your code is not performance critical, it may be easier to have a table of tables instead, something like:

lua Code:
  1. local buffs = { -- Unsorted buffs table
  2.     {1234, 25},
  3.     {4321, 60}
  4. }
  5.  
  6. for i, v in ipairs(buffs) do
  7.     print(i, v[1], v[2])
  8. end
  9.  
  10. --[[ Output:
  11. 1       1234    25
  12. 2       4321    60
  13. ]]
  14.  
  15. local function compare(a, b)
  16.     return a[2] > b[2]
  17. end
  18.  
  19. table.sort(buffs, compare)
  20.  
  21. for i, v in ipairs(buffs) do
  22.     print(i, v[1], v[2])
  23. end
  24.  
  25. --[[ Output:
  26. 1       4321    60
  27. 2       1234    25
  28. ]]
  29.  
  30. -- Now to find a specific buff ID and get the healing value, you could use something like:
  31.  
  32. local function getHealing(id)
  33.     for _, v in ipairs(buffs) do
  34.         if v[1] == id then return v[2] end
  35.     end
  36.     return nil -- Functions return nil by default, but whatever
  37. end
  38.  
  39. local healing = getHealing(1234) -- Returns 25
  40. healing = getHealing("this buff does not exist") -- Returns nil
  Reply With Quote