Looping over array values in Lua

Jeroen De Dauw picture Jeroen De Dauw · Oct 12, 2016 · Viewed 21.7k times · Source

I have a variable as follows

local armies = {
    [1] = "ARMY_1",
    [2] = "ARMY_3",
    [3] = "ARMY_6",
    [4] = "ARMY_7",
}

Now I want to do an action for each value. What is the best way to loop over the values? The typical thing I'm finding on the internet is this:

for i, armyName in pairs(armies) do
    doStuffWithArmyName(armyName)
end

I don't like that as it results in an unused variable i. The following approach avoids that and is what I am currently using:

for i in pairs(armies) do
    doStuffWithArmyName(armies[i])
end

However this is still not as readable and simple as I'd like, since this is iterating over the keys and then getting the value using the key (rather imperatively). Another boon I have with both approaches is that pairs is needed. The value being looped over here is one I have control over, and I'd prefer that it can be looped over as easily as possible.

Is there a better way to do such a loop if I only care about the values? Is there a way to address the concerns I listed?

I'm using Lua 5.0 (and am quite new to the language)

Answer

Yu Hao picture Yu Hao · Oct 12, 2016

The idiomatic way to iterate over an array is:

for _, armyName in ipairs(armies) do
    doStuffWithArmyName(armyName)
end

Note that:

  1. Use ipairs over pairs for arrays
  2. If the key isn't what you are interested, use _ as placeholder.

If, for some reason, that _ placeholder still concerns you, make your own iterator. Programming in Lua provides it as an example:

function values(t)
  local i = 0
  return function() i = i + 1; return t[i] end
end

Usage:

for v in values(armies) do
  print(v)
end