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 for writing:

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

I never use k, so I would like to pull it out of the path control, so it’s clear that I am just looping over the values. Is there a function like pairs () that gives me only a list of values?

+6
source share
5 answers

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

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

But usually people just use pairs and discard the first variable. In this case, it is customary to designate the unused variable _ (underscore) to clearly indicate the intention.

+10
source

I saw people use the variable _ instead of k or i.

+5
source

why do you use the pairs () function if you do not want the key / value pairs to be listed?

for example, this is even shorter:

 local t = {"asdf", "sdfg", "dfgh"} for i=1, #t do print(t[i]) end 

otherwise, I always did this:

 local t = {"asdf", "sdfg", "dfgh"} for _,v in pairs(t) do print(v) end 

edit: for your scenario, where you want to list only the values ​​in a table with non-numeric keys, perhaps the brightest thing you could do is write your own table iterator function as follows:

 local t = {["asdf"] = 1, ["sdfg"] = 2, ["dfgh"] = 3} function values(tbl) local key = nil return function() key = next(tbl, key) return tbl[key] end end for value in values(t) do print(value) end 

it’s very clear that you are only passing the values ​​of table t. Like pairs (), this is not guaranteed to go in order, since it uses next ().

+1
source

This is your coding style, really. If you can read it, and you agree with it, then it does not matter.

However, I tend to use: for i,c in "i" for "index" and "c" for "child", but "v" for "value" also works. And even if you are not using an index variable, this is still good practice.

One more thing you can do: for n = 1, 10 when dealing with numbers. But again, it's you coding style, and as long as it matches, you have to be good.

0
source

From the Lua Style Guide :

 The variable consisting of only an underscore "_" is commonly used as a placeholder when you want to ignore the variable: for _,v in ipairs(t) do print(v) end Note: This resembles the use of "_" in Haskell, Erlang, Ocaml, and Prolog languages, where "_" takes the special meaning of anonymous (ignored) variables in pattern matches. In Lua, "_" is only a convention with no inherent special meaning though. Semantic editors that normally flag unused variables may avoid doing so for variables named "_" (eg LuaInspect is such a case). 

Therefore, I would expect the name underscore ( _ ) to be more readable for unused variables.

0
source

Source: https://habr.com/ru/post/925245/


All Articles