Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable _ in lua has a special meaning?

Tags:

variables

lua

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?

like image 559
Alejandro Simkievich Avatar asked Dec 26 '15 22:12

Alejandro Simkievich


People also ask

What are variables in Lua?

Advertisements. A variable is nothing but a name given to a storage area that our programs can manipulate. It can hold different types of values including functions and tables. The name of a variable can be composed of letters, digits, and the underscore character.

Can you do ++ in Lua?

++ is not a C function, it is an operator. So Lua being able to use C functions is not applicable.


2 Answers

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

like image 127
DavisDude Avatar answered Sep 18 '22 02:09

DavisDude


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.

like image 39
warspyking Avatar answered Sep 19 '22 02:09

warspyking