How to iterate through table in Lua?

Lemony Lime picture Lemony Lime · Jul 3, 2013 · Viewed 131k times · Source

So, I have a table something along these lines:

arr =
{
  apples = { 'a', "red", 5 },
  oranges = { 'o', "orange", 12 },
  pears = { 'p', "green", 7 }
}

It doesn't seem like it's possible to access them based on their index, and the values themselves are tables, so I just made the first value of the nested table the index of it, so it now looks like this:

arr =
{
  apples = { 0, 'a', "red", 5 },
  oranges = { 1, 'o', "orange", 12 },
  pears = { 2, 'p', "green", 7 }
}

So, now any time I use one of these tables, I know what the index is, but still can't get to the table using the index, so I started to write a function that loops through them all, and check the indexes until it finds the right one. Then I realized... how can I loop through them if I can't already refer to them by their index? So, now I'm stuck. I really want to be able to type arr.apples vs arr[1] most of the time, but of course it's necessary to do both at times.

Answer

greatwolf picture greatwolf · Jul 3, 2013

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