Forum

> > CS2D > Scripts > _, in lua
ForenübersichtCS2D-Übersicht Scripts-ÜbersichtEinloggen, um zu antworten

Englisch _, in lua

2 Antworten
Zum Anfang Vorherige 1 Nächste Zum Anfang

alt _, in lua

kch
User Off Offline

Zitieren
hey,

i've got a question.
is there any difference in writing _, ?

as example

1
2
usgn = { "2422", "2552", "3521"}
for usgnid in usgn do
1
for _, usgnId in usgn do

alt Re: _, in lua

Masea
Super User Off Offline

Zitieren
Yes. There is.

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:
t = {2, 2, 2}

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.

alt Re: _, in lua

VADemon
User Off Offline

Zitieren
_
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.

1
2
3
4
-- One
for k,v in pairs(table) do
print(k,v)
end
1
2
3
4
-- Two
for _,v in pairs(table) do
print(_,v)
end
1
2
3
4
-- Three
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
Zum Anfang Vorherige 1 Nächste Zum Anfang
Einloggen, um zu antworten Scripts-ÜbersichtCS2D-ÜbersichtForenübersicht