Lua: Nil
| Lua |
|---|
|
| Basics |
| Intermediate |
| Advanced |
|
| XLua |
| Add to this template |
Nil is a special datatype in Lua, signifying the lack of useful data. Lua uses nil for various purposes; a nil index in a table is considered the end of the table, and function parameters that aren't used are assigned nil. Nil is also the default "value" for undefined variables. Nil and false are the only two values that are truly "false"; 0 and the empty string are considered "true".
Nil (along with false) is often used with the 'or' operator as an easy and clean way to assign a fallback or default value to a variable if it would otherwise be assigned nil. For example:
local x = objectName(y) or "NULL"
Assume that 'objectName()' returns the "name" string stored in the table of its parameter (in this case, table 'y'), or returns 'false' if there is no string there.
If there is actually a "name" string contained in the table, Lua will assign the contents of that string to 'x'. If there is no "name" string (returning false or nil), Lua will instead notice the 'or' and assign the string to the right of it instead, making x = "NULL"; Lua will not evaluate the right-hand side of an 'or' expression unless the left-hand side is nil or false.
Though both nil and false evaluate to false, they are of course different datatypes; using the type() function on each will verify this:
- type(false) --> "boolean"
- type(nil) --> "nil"
