Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over array values in Lua

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)

like image 282
Jeroen De Dauw Avatar asked Oct 12 '16 06:10

Jeroen De Dauw


People also ask

How do I iterate over a table in Lua?

For tables using numeric keys, Lua provides an ipairs function. The ipairs function will always iterate from table[1] , table[2] , etc. until the first nil value is found. A final way to iterate over tables is to use the next selector in a generic for loop.

What is a for loop Lua?

Advertisements. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

What is pairs Lua?

pairs(table) Lua provides a pairs() function to create the explist information for us to iterate over a table. The pairs() function will allow iteration over key-value pairs. Note that the order that items are returned is not defined, not even for indexed tables.


1 Answers

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
like image 156
Yu Hao Avatar answered Oct 20 '22 01:10

Yu Hao