Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more readable way to write for k, v in pairs(my_table) do ... end in lua if I never use k?

Is there a more readable way in lua to write:

for k, v in pairs(my_table) do
    myfunction( v )
end 

I'm never using k, so I'd like to take it out of the loop control, so it's clear I'm just iterating over the values. Is there a function like pairs() that only gives me a list of the values?

like image 458
Ecnassianer Avatar asked Sep 12 '12 19:09

Ecnassianer


1 Answers

There is no standard function that only iterates values, but you can write it yourself if you wish. Here is such an iterator :

function values(t)
  local k, v
  return function()
    k, v = next(t, k)
    return v
  end
end

But normally people just use pairs and discard the first variable. It is customary in this case to name the unused variable _ (an underscore) to clearly indicate the intent.

like image 87
prapin Avatar answered Nov 15 '22 11:11

prapin