What is nil in Lua?

Share

Introduction

In Lua, there is a single value type called nil. Lua uses this type as a non-value to represent the absence of a valid value. The main property of nil is that it is different from any other type in the language.

Usage

nil is assigned to every global variable we create by default. We can also set nil to a global variable to delete it.

Note: nil is also useful if you want to delete object instances and array elements.

Example

In this example, we use nil to delete a variable.

x = 1
print(x)
x = nil
print(x)
x = {
zero = 0,
one = 1
}
x.zero = nil
print(x.zero)