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.
local variableToDelete = 5print(variableToDelete) -- 5variableToDelete = nilprint(variableToDelete) -- nillocal dictionaryTable = {Monday = 1,Tuesday = 2,Wednesday = 3}-- Output value of 'Tuesday' keyprint(dictionaryTable.Tuesday) -- 2-- Clear 'Tuesday' keydictionaryTable.Tuesday = nil-- Output value of key againprint(dictionaryTable.Tuesday) -- nil
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:
-- Create a new bricklocal part = Instance.new("Part")-- Parent new Part to the workspace, making it viewablepart.Parent = workspacetask.wait(1)-- Remove the Part from view, but not from memorypart.Parent = niltask.wait(1)-- Part still exists because it's referenced by the variable 'part', so it can be returned to viewpart.Parent = workspacetask.wait(1)-- Remove the part from view againpart.Parent = nil-- Clear part reference so it gets picked up by the garbage collectorpart = nil