Iterate on map using for


#1

Hi,

I have a little question on how iterate on a map, I know there is for_each function but it causes scope problem, the problem is that for_each take as argument a function that has no access on variables defines in the current scope :

var aValue = 1.
var myMap = ["a" : 0.8, "b" : 1.2]
myMap.for_each(fun(myMapValue)
{
  if (myMapValue.second > aValue)
  {
    print("${myMapValue.first} is over a aValue")
  }
  else
  {
    print("${myMapValue.first} is behind a aValue")
  }
})

this code don’t work because the function doesn’t know aValue variable, so I have to set all my variables as global to make my for loops works… It is a bit invasive for a “simple” loop.

Is there a more elegant solution ?

Thank you


#2

You have two options.

First: keep your current loop but capture the values you want in the lambda.

var aValue = 1.
var myMap = ["a" : 0.8, "b" : 1.2]
myMap.for_each(fun[aValue](myMapValue)
{
  if (myMapValue.second > aValue)
  {
    print("${myMapValue.first} is over a aValue")
  }
  else
  {
    print("${myMapValue.first} is behind a aValue")
  }
})

Second: do a while loop over the range object

var m = ["x":1, "y":2]
var r = range(m)

while (!r.empty()) { 
  print("${r.front().first()}=${r.front().second()}"); 
  r.pop_front()); 
}

Adding proper support for range-based for loops is on my todo list!


#3

Oh great ! I don’t know capture were implemented, this is perfect for me !

Thank you once again !