Nil

< Scripting | Data Types

By definition, nil is a state of non-existence or nothingness. In Lua, nil is a non-initialized value, and is a special value used to represent nothing. It represents the absense of a useful value. Math cannot be performed on nil or anything equivalent to nil, because nothing, unlike 0, is not a numerical value.

Use cases[edit]

Nil can be used to blank the value of a property of an object of type Instance. It can also be used to change a number property in an instance to 0 although it is good practice to set it to 0 instead. It is very common to set the Parent of an object to nil, which removes it from the game. However, it is possible to bring the object back unless you use the Destroy method. For example, if the object is referenced by a variable, you can set its Parent property again and bring the object back. Nil can also be used to remove a value in a table or destroy a variable in a script.

Example
Example script of referencing an object.
p = Instance.new('Part') -- Create a new brick
p.Parent = Workspace -- The part (a grey brick, by default) has a parent, the workspace
wait(1)
p.Parent = nil -- The part now has no parent (and so it disappears from view, but not from memory).
wait(1)
p.Parent = Workspace -- part still exists because it is referenced by the variable 'p'
wait(1)
p.Parent = nil -- part disappears again (it has no parent)
p = nil -- part is no longer referenced by anything, so it gets picked up by the garbage collector

Look through the comments in the script above to understand why recovering an object by reference is possible.

Here is an example of removing something from a table:

Example
local tbl = {Monday = 1, Tuesday = 2, Wednesday = 3}
print(tbl.Tuesday)
tbl.Tuesday = nil
print(tbl.Tuesday)
2
nil


See also[edit]