Looping over array values in Lua

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)