Nil

In Luau, nil represents non-existence or nothingness. It's different from any other value or data type. You can use it to destroy a variable or remove a value in a table. It's the only value other than false which doesn't evaluate to true.

Luau has a garbage collector that removes data that is no longer accessible by any script. For best performance, redefine large variables as nil in long-running scripts when you don't need them anymore so the garbage collector removes them.


1local variableToDelete = 5
2print(variableToDelete) -- 5
3variableToDelete = nil
4print(variableToDelete) -- nil
5
6local dictionaryTable = {
7 Monday = 1,
8 Tuesday = 2,
9 Wednesday = 3
10}
11-- Output value of 'Tuesday' key
12print(dictionaryTable.Tuesday) -- 2
13-- Clear 'Tuesday' key
14dictionaryTable.Tuesday = nil
15-- Output value of key again
16print(dictionaryTable.Tuesday) -- nil
17

You can use nil to clear some properties of objects. For example, you can set the Parent of an object to nil to effectively remove the object from the experience. To return the object to the experience after you remove it, reassign the Parent. The following example demonstrates how to use nil to remove a Part:


1-- Create a new brick
2local part = Instance.new("Part")
3-- Parent new Part to the workspace, making it viewable
4part.Parent = workspace
5wait(1)
6-- Remove the Part from view, but not from memory
7part.Parent = nil
8wait(1)
9-- Part still exists because it's referenced by the variable 'part', so it can be returned to view
10part.Parent = workspace
11wait(1)
12-- Remove the part from view again
13part.Parent = nil
14-- Clear part reference so it gets picked up by the garbage collector
15part = nil
16