Lua: Nil
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
Nil
Nil is a special datatype in Lua. It is a symbol representing that there is no data at all.
The nil index of a table signifies the end of said table, and any function parameter that is not used or does not exist is also nil. Undefined variables within expressions, or defined variables with no value assigned, are assumed to be nil, as are variables set to the result of a function with no return value.
nil is not valid as a key or value within a table, although missing indices within an array will be considered nil.
nil is the only valid substitute for the boolean value false; 0 and any "empty" value (such as the "" string) are still true in boolean comparison.
Behavior of nil
Use in conditional statements
nil may be used with the or operator to create shortcuts in code:
local x = objectName(y) or "NULL"
Assume that objectName() returns the name string in its table y.
If there is such a name string, the x variable shall now contain it.
Otherwise, false or more likely nil are returned. In this case - and only in this csae - Lua will respond to the or operator and assign the string to its right instead, this being "NULL".
Type() function
Although nil and false are generally equivalent, nil is its own type, whereas false is a boolean value, as seen with the type() function:
type(false) --> "boolean"
type(nil) --> "nil"
Scope
Declaring a global variable with a value, declaring a local variable of the same name with no value, and returning this local varabile, will return nil:
var = 10 -- global variable 'var'
function test1()
print(var) -- accesses the global variable 'var'
end
function test2()
local var -- Defines a new local variable, also named 'var'
print(var) -- accesses the local 'var', not the global one
end
test1() --> 10; the global 'var' was assigned this value
test2() --> nil; the local 'var' was not assigned any value