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 green
apples 0 a red
oranges 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)
end
table.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 = apples
arr[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 + ipairsCompatable
1 AAA
2 BBB
3 CCC
ipairs + ipairsCompatable2
1 DDD
2 EEE
3 FFF
ipairs + ipairsCompatable3
1 this
2 does
3 work
ipairs + notIpairsCompatable
pairs + notIpairsCompatable
2 this
3 does
4 not
ipairs + notIpairsCompatable2
pairs + notIpairsCompatable2
2 this
5 doesnt
24 either
ipairs + kindofIpairsCompatable
1 1
2 2
3 3
pairs + kindofIpairsCompatable
1 1
2 2
3 3
5 5
cool bro