20

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?

1
  • Some IDEs will give you a warning if you declare a variable and don't use it, or assign it a new value without using the previous value. Respecting the conventional use of _ as a throwaway variable, they obviously wouldn't do that for _ even though it is just an ordinary variable. Commented Dec 28, 2015 at 17:45

2 Answers 2

30

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).

0
18

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.

3
  • 1
    I had more information than the other answer to offer up to the table, so I posted my own answer. I hope it helps.
    – warspyking
    Commented Dec 27, 2015 at 0:28
  • it certainly does warspyking! Commented Dec 27, 2015 at 7:29
  • If I left anything out feel free to tell me, I'd love to make the answer more informative.
    – warspyking
    Commented Dec 27, 2015 at 16:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.