Reputation: 3792
I am a newbie to lua / torch. I notice that the variable _ is used a lot, especially in iterators. Example:
for _, node in ipairs(protos.rnn.forwardnodes) do
a, b = whatever(a,b)
end
this 'variable naming convention' (so to speak) is used in other circumstances as well, as in:
local _,loss = optimizer(feval,params, optim_state)
Does _ have any special meaning or is it just one more variable name, among the many possible names?
Upvotes: 22
Views: 26829
Reputation: 3113
The use of _ is usually for returning values you don't want from a function. Which makes sense, it looks like a blank. The reason it's commonly used when iterating is because most iterators return key,value pairs, and you only need the value.
However, _ can also be used for the exact opposite. When placed behind a variable, such as _G
or _VERSION
, it signifies it is important and shouldn't be changed.
And finally, the double underscore. I've only ever used these for metamethods, such as __index
or __add
, so if you're making a function or API or whatever that checks for a custom metamethod, make sure to be consistent, and use a double underscore.
So in the end, it's just a naming convention, and is totally opinionated and optional.
Upvotes: 19
Reputation: 952
It's usually used as a throwaway variable. It has no "real" special meaning, but is used to signify that the indicated value is not important.
The variable consisting of only an underscore "_" is commonly used as a placeholder when you want to ignore the variable...
Read more here (under the naming portion).
Upvotes: 31