Page 1 of 1

Role of "_" in for loops?

Posted: Tue Jun 12, 2012 7:09 am
by onedaysnotice
Hi, I'm kinda learning lua as I program my game, so theres many parts of the language I'm still unsure of. So to the point, whilst studying people's codes I've noticed numerous times that "_" (without quotes) have been used instead of i. Is there a difference between just using i, and underscore? If so, what is its purpose?

An example of what I'm referring to:

for _,v in ipairs() do
-etc
end

thanks :D

Re: Role of "_" in for loops?

Posted: Tue Jun 12, 2012 7:18 am
by dreadkillz
I think its to indicate that its a non important variable when you're reading your code. At least that's what I use it for.

Re: Role of "_" in for loops?

Posted: Tue Jun 12, 2012 7:33 am
by kikito
It's a readability thing.

The code will "work" both ways - with a k or with _. But with the underscore you make clear that "you are not going to use this variable at all".

Another typical example is when you have a function that returns several values. For example, string.find returns the position of the first character and the last character of a pattern found in a string. If you are going to use only the "end position", and don't care about the start, you can do this:

Code: Select all

local _, endPos = string.find("Where does Lua end?", "Lua")
print("Lua ends in the " .. tostring(endPos) .. " character")

Re: Role of "_" in for loops?

Posted: Tue Jun 12, 2012 9:40 am
by onedaysnotice
Ok thanks heaps guys :D

Re: Role of "_" in for loops?

Posted: Tue Jun 12, 2012 3:08 pm
by josefnpat
From the Lua Style Guide: http://lua-users.org/wiki/LuaStyleGuide

The variable consisting of only an underscore "_" is commonly used as a placeholder when you want to ignore the variable:

for _,v in ipairs(t) do print(v) end
Note: This resembles the use of "_" in Haskell, Erlang, Ocaml, and Prolog languages, where "_" takes the special meaning of anonymous (ignored) variables in pattern matches. In Lua, "_" is only a convention with no inherent special meaning though. Semantic editors that normally flag unused variables may avoid doing so for variables named "_" (e.g. LuaInspect is such a case).

Re: Role of "_" in for loops?

Posted: Tue Jun 12, 2012 6:42 pm
by Jasoco
It's just a throwaway. It signifies that it's not important and won't be used, but is there because something needs to be there. So instead of using say, "i" or "n", just use the underscore as it's easier to work around in case you do need to use i or n later.