We use cookies on this site to enhance your user experience

Jul 03 2018, 10:55 AM PST 2 min

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

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.

p = Instance.new('Part') -- Create a new brick
p.Parent = Workspace -- The part (a grey brick, by default) has a parent, the workspace
p.Parent = nil -- The part now has no parent (and so it disappears from view, but not from memory).
p.Parent = Workspace -- part still exists because it is referenced by the variable 'p'
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:

  • lua
  • coding
  • concept