_, in lua
2 replies



11.02.21 04:14:49 pm
hey,
i've got a question.
is there any difference in writing _, ?
as example
i've got a question.
is there any difference in writing _, ?
as example
Code:
1
2
2
usgn = { "2422", "2552", "3521"}
for usgnid in usgn do
for usgnid in usgn do
Code:
1
for _, usgnId in usgn do
Yes. There is.
First of all in your code block you haven't used
When you call
This will output: 1, 2, 3.
However, when you want to get the values as well, you will always have to get the key values too.
Thus, typically, programmers just use "_" for the keys when the only thing they care about is the values.
First of all in your code block you haven't used
pairs()
, so I don't know if that even works or there is any difference.When you call
pairs(<table>)
, it iterates through the keys and the corresponding values for each element in the table. You are both able to get the key and value. But, technically, you don't have to get both at the same time. You may only want to get the key value, having no need for the value:Code:
t = {2, 2, 2}
for k in pairs(t) do
print(k)
end
for k in pairs(t) do
print(k)
end
This will output: 1, 2, 3.
However, when you want to get the values as well, you will always have to get the key values too.
Thus, typically, programmers just use "_" for the keys when the only thing they care about is the values.
Create your UI easy and fast: UI Framework | Go deeper into the darkness and test your bravery:
Outlast II Mod (28)


_
is a normal variable name character in Lua. Any of [0-9A-Za-z_] are legal variable characters.Therefore "_" is a regular variable in Lua.
Code:
1
2
3
4
2
3
4
-- One
for k,v in pairs(table) do
print(k,v)
end
for k,v in pairs(table) do
print(k,v)
end
Code:
1
2
3
4
2
3
4
-- Two
for _,v in pairs(table) do
print(_,v)
end
for _,v in pairs(table) do
print(_,v)
end
Code:
1
2
3
4
2
3
4
-- Three
for _key,v in pairs(table) do
print(_key,v)
end
for _key,v in pairs(table) do
print(_key,v)
end
Practically, however, even the book Programming in Lua says that the underscore "_" is a placerholder for unneeded return values in places such as pairs. You show that you don't need the first value here and only want the 2nd one.
In theory it could be exploited by a JIT compiler to completely dismiss assignments to "_" for performance reasons, although it would be violating the Lua spec, which has no special meaning for "_" variable and treats it like any other variable.
You can read paraphrased (other) explanations there: https://stackoverflow.com/questions/34475995/variable-in-lua-has-a-special-meaning/34476522#34476522



