1) _
is treated by Lua as a letter: exactly the same as A
or e
or F
. For stylistic purposes, it's sometimes used as a word or namespace separator: Ex.: apple_pie
sourceEngine_lightFires
When it precedes a name, it usually indicates that the name is somehow special or not intended to be accessed. For instance, a helper function for a factorial may be called _factorial
, and the function you are supposed to call is called factorial
. Other examples are the metamethods, which are all preceded by two underscores: Ex.: __index
Finally, sometimes we use a single underscore to indicate that a variable is not important. Because of how multiple returns work in Lua, this is sometimes necessary.
For example, string.find
locates the first and last characters of a found string. So if we only cared about the last character, we might see someone doing something like this:
1 | _,last = str:find( "cat" ); |
All of this said, those are just common stylistic considerations. There is nothing special about the underscore.
All of the following are valid, normal names that act like any other function or variable name:
2 | _sdofij_WOEIJFOIJ___SDOIFJOSDIJ |
2) pairs
and ipairs
both iterate over tables. pairs
iterates over all keys/properties/indices, while ipairs
only iterates over those which are counted in table length (#
), which are the values 1
, 2
, 3
,... until a value is found which is nil
.
This means that only "a","b","c" will be printed out for the following, even though the positive integer key 5 is defined for the table:
1 | local t = { "a" , "b" , "c" , "d" , "e" } ; |
4 | print ( "t[" ,i, "] = " ,v); |
Locked by adark and Articulating
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?