How to iterate through table in Lua? How to iterate through table in Lua? arrays arrays

How to iterate through table in Lua?


To iterate over all the key-value pairs in a table you can use pairs:

for k, v in pairs(arr) do  print(k, v[1], v[2], v[3])end

outputs:

pears   2   p   greenapples  0   a   redoranges 1   o   orange

Edit: Note that Lua doesn't guarantee any iteration order for the associative part of the table. If you want to access the items in a specific order, retrieve the keys from arr and sort it. Then access arr through the sorted keys:

local ordered_keys = {}for k in pairs(arr) do    table.insert(ordered_keys, k)endtable.sort(ordered_keys)for i = 1, #ordered_keys do    local k, v = ordered_keys[i], arr[ ordered_keys[i] ]    print(k, v[1], v[2], v[3])end

outputs:

  apples  a   red     5  oranges o   orange  12  pears   p   green   7


If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.

arr = {}apples = {'a', "red", 5 }arr.apples = applesarr[1] = apples

This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):

for k,v in pairs(t) do print(k,v)end


For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable1       AAA2       BBB3       CCCipairs + ipairsCompatable21       DDD2       EEE3       FFFipairs + ipairsCompatable31       this2       does3       workipairs + notIpairsCompatablepairs + notIpairsCompatable2       this3       does4       notipairs + notIpairsCompatable2pairs + notIpairsCompatable22       this5       doesnt24      eitheripairs + kindofIpairsCompatable1       12       23       3pairs + kindofIpairsCompatable1       12       23       35       5cool    bro