View Single Post
03-23-18, 10:36 AM   #4
MunkDev
A Scalebane Royal Guard
 
MunkDev's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2015
Posts: 431
Lua Code:
  1. for i=1, #mydata do
  2.     local value = mydata[i]
  3.     -- do something with value in sequential array
  4. end
  5.  
  6. for i, value in ipairs(mydata) do
  7.     -- do something with value in sequential array
  8. end
  9.  
  10. for i, value in pairs(mydata) do
  11.     -- do something with value in associative array
  12. end
  13.  
  14. mydata[#mydata + 1] = newValue -- append sequential
  15. mydata["index"] = newValue -- insert associative
  16. mydata[5] = newValue -- insert associative
  17.  
  18. table.insert(mydata, 1, newValue) -- prepend (put newValue at mydata[1])
  19. table.insert(mydata, newValue) -- append (put newValue at mydata[#mydata + 1])

To explain what pairs and ipairs do, they essentially just return an index key and value associated with that key in pairs.
Lua Code:
  1. -- pairs, literally just a wrapper of std next
  2. function pairs (t)
  3.     return next, t, nil
  4. end
  5.  
  6. -- ipairs, does an incremental lookup and stops when the value is nil
  7. local function iter (a, i)
  8.     i = i + 1
  9.     local v = a[i]
  10.     if v then
  11.         return i, v
  12.     end
  13. end
  14.  
  15. function ipairs (a)
  16.     return iter, a, 0
  17. end

When to use pairs/ipairs?
  • pairs - associative arrays, keys are non-numerical or not in sequence starting at 1.
  • ipairs - numerically indexed arrays where there are no gaps between [1] and however many elements the table has.
__________________

Last edited by MunkDev : 03-23-18 at 10:55 AM.
  Reply With Quote